简体   繁体   English

Python:找出一个数的两个质因数。 如何让这段代码更有效率?

[英]Python: Find the two prime factors of a number. how to make this code more efficiency?

在此处输入图像描述

My current code:我当前的代码:

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))

My code can meet most test case;我的代码可以满足大多数测试用例; But if the input is 603091532958059 then the answer will be (24557917, 24557927);但是如果输入是 603091532958059 那么答案就是 (24557917, 24557927); But it will take more than 1 second to finish ( Time limit exceeded );但是完成需要超过 1 秒(超出时间限制);

Any suggestion?有什么建议吗? Thank you!谢谢!

To speed up your code you could use Fermat's factorization method , as @PM 2Ring told in comments.为了加快您的代码速度,您可以使用Fermat 的分解方法,正如 @PM 2Ring 在评论中所说的那样。 Try following code试试下面的代码

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
        b = int(math.sqrt(b2))
    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM