Example of factorization of a number implemented by Python

  • 2021-07-03 00:34:13
  • OfStack

In this paper, an example is given to describe the factorization operation of one number realized by Python. Share it for your reference, as follows:

In mathematics, we may factorize a number. How can we do it with Python? The following is an algorithm written by a big brother. Just take it here and use it directly.


#  Right 1 The number is factorized 
def factorization(num):
  factor = []
  while num > 1:
    for i in range(num - 1):
      k = i + 2
      if num % k == 0:
        factor.append(k)
        num = int(num / k)
        break
  return factor

We call this function and introduce the time library for time calculation


st = time.perf_counter()
print(factorization(707829217))
et = time.perf_counter()
print(" Time :", et - st)

You can see that the final print result is:

[8171, 86627]
Time: 0.0064456

It can be seen that factorization is still very fast, so thank you very much here ~

Finally, the full version is attached for everyone to use (copy it into your IDE, and then just modify the numbers.)


import time
#  Right 1 The number is factorized 
def factorization(num):
  factor = []
  while num > 1:
    for i in range(num - 1):
      k = i + 2
      if num % k == 0:
        factor.append(k)
        num = int(num / k)
        break
  return factor
st = time.perf_counter()
print(factorization(707829217))
et = time.perf_counter()
print(" Time :", et - st)

Run results:

[8171, 86627]
Time: 0.039954294630645655

PS: Here are some computing tools recommended for your reference in the next step:

On-line decomposition prime factor calculator tool:
http://tools.ofstack.com/jisuanqi/factor_calc

On-line 1 yuan function (equation) solution calculation tool;
http://tools.ofstack.com/jisuanqi/equ_jisuanqi

Scientific calculator online _ advanced calculator online calculation:
http://tools.ofstack.com/jisuanqi/jsqkexue

Online Calculator _ Standard Calculator:
http://tools.ofstack.com/jisuanqi/jsq

For more readers interested in Python related contents, please check the topics of this site: "Summary of Python Mathematical Operation Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills", "Introduction and Advanced Classic Tutorial of Python" and "Summary of Python File and Directory Operation Skills"

I hope this article is helpful to everyone's Python programming.


Related articles: