【问题标题】:Python: Find the two prime factors of a number. how to make this code more efficiency?Python:找出一个数的两个质因数。如何让这段代码更有效率?
【发布时间】:2018-04-08 20:49:58
【问题描述】:

我当前的代码:

import math
def factorMe(value):
last = int(math.sqrt(value)+1)
for i in range(2,last):
    if value %i ==0:
        return (i,int(value/i))

我的代码可以满足大多数测试用例;但是如果输入是 603091532958059 那么答案将是 (24557917, 24557927);但是需要超过 1 秒才能完成(超过时间限制);

有什么建议吗?谢谢!

【问题讨论】:

标签: python processing-efficiency


【解决方案1】:

要加速您的代码,您可以使用Fermat's factorization method,正如@PM 2Ring 在 cmets 中所说的那样。试试下面的代码

import math
def factorMe(value):
    last = int(math.sqrt(value)+1)
    # check if value is even
    if value % 2 == 0:
        return (2, int(value / 2))
    # value is odd number
    a = int(math.sqrt(value)) + 1
    b2 = int(a * a - value)
    b = int(math.sqrt(b2))
    while b ** 2 != int(b2):
        a += 1
        b2 = a * a - value
    return (int(a - math.sqrt(b2)), int(a + math.sqrt(b2)))


v = 603091532958059
%timeit r = factorMe(v)
print(r)

100000 loops, best of 3: 2.15 µs per loop
(24557917, 24557927)

【讨论】:

    猜你喜欢
    • 2013-06-13
    • 1970-01-01
    • 2012-04-01
    • 2020-08-22
    • 2019-12-11
    • 1970-01-01
    • 2019-10-21
    • 2016-03-17
    • 1970-01-01
    相关资源
    最近更新 更多