Prime factor of 300 000 000 000?

前端 未结 19 807
无人及你
无人及你 2021-01-03 10:23

I need to find out the prime factors of over 300 billion. I have a function that is adding to the list of them...very slowly! It has been running for about an hour now and i

19条回答
  •  醉话见心
    2021-01-03 11:13

    Your algorithm must be FUBAR. This only takes about 0.1s on my 1.6 GHz netbook in Python. Python isn't known for its blazing speed. It does, however, have arbitrary precision integers...

    import math
    import operator
    
    def factor(n):
        """Given the number n, to factor yield a it's prime factors.
        factor(1) yields one result: 1. Negative n is not supported."""
        M = math.sqrt(n)  # no factors larger than M
        p = 2             # candidate factor to test
        while p <= M:     # keep looking until pointless
            d, m = divmod(n, p)
            if m == 0:
                yield p   # p is a prime factor
                n = d     # divide n accordingly
                M = math.sqrt(n)  # and adjust M
            else:
                p += 1    # p didn't pan out, try the next candidate
        yield n  # whatever's left in n is a prime factor
    
    def test_factor(n):
        f = factor(n)
        n2 = reduce(operator.mul, f)
        assert n2 == n
    
    def example():
        n = 600851475143
        f = list(factor(n))
        assert reduce(operator.mul, f) == n
        print n, "=", "*".join(str(p) for p in f)
    
    example()
    
    # output:
    # 600851475143 = 71*839*1471*6857
    

    (This code seems to work in defiance of the fact that I don't know enough about number theory to fill a thimble.)

提交回复
热议问题