Factorizing a number in Python

后端 未结 4 1311
灰色年华
灰色年华 2021-01-14 02:55

Here\'s my code:

def factorize(n):
    sieve = [True] * (n + 1)

    for x in range(2, int(len(sieve) ** 0.5) + 1):
        if sieve[x]: 
            for i i         


        
4条回答
  •  暖寄归人
    2021-01-14 03:34

    I'm not familiar enough to tell if this question should be deleted or whatever, but I'll help out anyhow.

    You have the sieve part correct, I think. The key is to use a while loop to keep on dividing out a valid prime factor more than once.

    factors = []
    sieve[0] = sieve[1] = False # So I don't have to worry about trying to skip over these two
    for testFactIndex, isPrime in enumerate(sieve):
        if isPrime:
            while n%testFactIndex == 0:
                n = n/testFactIndex
                factors.append(testFactIndex)
    return factors
    

提交回复
热议问题