首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >数字因子分解。Python [暂停]?

数字因子分解。Python [暂停]?
EN

Stack Overflow用户
提问于 2018-09-04 05:54:07
回答 1查看 0关注 0票数 0

我学了一个星期的python。刚写了一个代码,找到任何数字的所有因子。

代码语言:javascript
复制
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)

结果如下:

代码语言:javascript
复制
Give M: 9999999999999999
3333333333333333
1111111111111111
101010101010101
5941770647653
81394118461
805882361
5882353
[3, 3, 11, 17, 73, 101, 137, 5882353]

有没有人写类似的东西?我在这里发布我的代码。随意发表评论,我想知道代码是否可以更简单并获得相同的结果。谢谢!!!!

EN

回答 1

Stack Overflow用户

发布于 2018-09-04 15:18:03

代码语言:javascript
复制
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]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100002555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档