python 使用递归法对整数进行因数分解

 1 from random import randint
 2 
 3 def factors(num, fact = []):
 4     #每次从2开始查找因数
 5     for i in range(2, int(num**0.5) + 1):
 6         if num % i == 0:
 7             fact.append(i)
 8             factors(num // i, fact)
 9             break
10     else:
11         fact.append(num)
12 
13 facts = []
14 n = randint(2, 10**8)
15 factors(n, facts)
16 result = '*'.join(map(str, facts))#把facts里的元素,全部转化成字符
17 #并用*号连接起来,形成一个长的字符串 表达式
18 if n == eval(result):
19     print(n, '= ' + result)
原文地址:https://www.cnblogs.com/letianpaiai/p/13864227.html