代码:
#!/usr/bin/env python
# unique factorization
# e.g
# 7 is a prime number
# 6000 = [2^4]*[3^1]*[5*3]
import sys
def uniq_fac(num):
'''
unique factorization of integer num
return a tuple (flag, prime-list, index-list)
flag: num is prime or not
prime-list: [p1, p2, ...pr]
index-list: [e1, e2, ...er]
'''
if not isinstance(num, int):
print num, 'not an integer'
sys.exit(1)
flag = 1
prime_list = []
index_list = []
for i in xrange(2, num/2+1):
if num%i == 0:
prime_list.append(i)
idx = 0
while num%i == 0:
num = num/i
idx += 1
index_list.append(idx)
flag = 0
return (flag, prime_list, index_list)
def test_uniq_fac(num):
(flag, prime_list, index_list) = uniq_fac(num)
if flag:
print num, 'is a prime'
else:
print num, '= ',
for i in range(0, len(prime_list)):
print '[%d^%d]' % (prime_list[i], index_list[i]),
if not i==len(prime_list)-1:
print '*',
print
def test(argv):
for num in argv:
test_uniq_fac(int(num))
if __name__ == '__main__':
test(sys.argv[1:])
测试示例:
./unique_factorization.py 3829374
3829374 = [2^1] * [3^2] * [19^1] * [11197^1]
来源:oschina
链接:https://my.oschina.net/u/158589/blog/101572