质因数分解

懵懂的女人 提交于 2020-12-18 03:22:46

代码:

#!/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]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!