Prime factorization of a number

家住魔仙堡 提交于 2020-03-02 09:28:47

问题


I'm trying to write a program to find all the prime factors of a given number, and tried the following:

def factors(nr):
    i = 2
    factors = []
    while i<nr:
        if (nr%i)==0:
            factors.append(i)
            nr = nr/i
        else:
            i = i+1
    return factors

My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?

I know that several right answers are posted on the site, but I would like to know why my program is incorrect.

Update So if I let the programm run for example:

factors(38), yields [2].

factors(25), yields [5].

So it stops after it has added one number to the list.


回答1:


The simplest change you can make to fix your problem is to change your while loop condition:

def factors(nr):
    i = 2
    factors = []
    while i <= nr:
        if (nr % i) == 0:
            factors.append(i)
            nr = nr / i
        else:
            i = i + 1
    return factors

print factors(8)
print factors(9)
print factors(10)

Output

[2, 2, 2]
[3, 3]
[2, 5]



回答2:


def ba(n):
    pfa=[]
    y=n
    for i in range(n):
        if (i!=0 and i!=1):
            while (y%i==0):
                pfa.append(i)
                y=y/i
    print(pfa)


来源:https://stackoverflow.com/questions/43129076/prime-factorization-of-a-number

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