我学了一个星期的python。刚写了一个代码,找到任何数字的所有因子。
import math
# A function to find the first factor, it will return None for prime
def factor(n):
for i in range(2,math.ceil(math.sqrt(1.1*n))):
if n%i==0:
return int(n/i)
m=int(input("Give M: "))
# A loop to find more factor, add it to list a, break when goes to prime
a=[]
k=m
q=0
while k>=0:
q=factor(k)
if q is None:
break
a.append(int(k/q))
k=factor(k)
print(k)
if k==2:
break
# check the lenght of list a, multiple all the element together in a, add
the final element (Input number/multiples just get) into a
b=len(a)
p=1
for j in range(0,b):
p=p*a[j]
a.append(int(m/p))
print(a)
结果如下:
Give M: 9999999999999999
3333333333333333
1111111111111111
101010101010101
5941770647653
81394118461
805882361
5882353
[3, 3, 11, 17, 73, 101, 137, 5882353]
有没有人写类似的东西?我在这里发布我的代码。随意发表评论,我想知道代码是否可以更简单并获得相同的结果。谢谢!!!!
发布于 2018-09-04 15:18:03
def facts(x):
output = []
i = 2
while x //i >0:
if x % i ==0:
output.append(i)
x //= i
else: i += 1
return(output)
print(facts(9999999999999999))
[3, 3, 11, 17, 73, 101, 137, 5882353]
https://stackoverflow.com/questions/-100002555
复制相似问题