Python implements a positive integer factorization prime factor operation example
- 2020-12-05 17:17:17
- OfStack
This article illustrates Python's implementation of positive integer factorization operation. To share for your reference, the details are as follows:
Encounter an Python programming exercise: Decompose a positive integer into prime factors. For example: type 90 and print 90=2*3*3*5.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def div_func(n):
result = []
while True:
for i in xrange(2, int(n**0.5) + 1):
if n % i == 0:
result.append(i)
n /= i
break
else:
result.append(n)
break
return ' * '.join(map(str, result))
num = raw_input('please enter a number( < 1.0E+18):')
try:
int_num = int(num)
if int_num > 10**18 or int_num < 0:
raise ValueError()
print div_func(int_num)
except ValueError:
print 'invalid number'
[
please enter a number(
<
1.0E+18):123124324324134334
2 X 293 X 313 X 362107 X 1853809
I wrote it myself, with no reference to other people's algorithms on the Internet. The results are pretty much the same as everyone else.
Recursion can also be used:
def factor(num):
if num == 1:
return []
else:
for i in range(2, num+1):
n, d = divmod(num, i)
if d == 0:
return [i] + factor(n)
for test_num in (299, 1024, 20, 7):
print(test_num, '->', ' * '.join(map(str, factor(test_num))))
[
299 -
>
13 * 23
1024 -
>
2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
20 -
>
2 * 2 * 5
7 -
>
7
PS: Here are a few more computing tools for you to refer to in the next step:
Online factorization prime factor calculator tool:
http://tools.ofstack.com/jisuanqi/factor_calc
Online 1 element function (equation) solving calculation tool:
http://tools.ofstack.com/jisuanqi/equ_jisuanqi
Scientific Calculators online Using _ Advanced calculators online calculation:
http://tools.ofstack.com/jisuanqi/jsqkexue
Online calculators _ Standard calculators:
http://tools.ofstack.com/jisuanqi/jsq
For more information about Python, please refer to Python Mathematical Operation Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Use Skills Summary, Python String Operation Skills Summary, Python Introduction and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.
I hope this article has been helpful for Python programming.