Factorizing a number in Python

后端 未结 4 1344
灰色年华
灰色年华 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:24

    The Sieve of Eratosthenes helps you find prime numbers below a certain limit. It's not really going to help you with finding the factors of a particular number.

    If you want to do that, the simplest approach that I can see is something like this:

    def factors(n):
        while n > 1:
            for i in range(2, n + 1):
                if n % i == 0:
                    n /= i
                    yield i
                    break
    
    for factor in factors(360):
        print factor
    

    This basically finds the smallest factor of n (which is guaranteed to be prime), divides n by that number and repeats the process until n is equal to 1.

    The output is:

    2
    2
    2
    3
    3
    5
    

    They multiply out to the original number:

    >>> from operator import mul
    >>> reduce(mul, factors(360))
    360
    

提交回复
热议问题