Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:找到一个数的两个素数因子。如何使此代码更高效?_Python_Processing Efficiency - Fatal编程技术网

Python:找到一个数的两个素数因子。如何使此代码更高效?

Python:找到一个数的两个素数因子。如何使此代码更高效?,python,processing-efficiency,Python,Processing Efficiency,我当前的代码: 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秒以上才能完成 有什么建议吗?谢谢大家! 如@PM 2Rin

我当前的代码:

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秒以上才能完成


有什么建议吗?谢谢大家!

如@PM 2Ring在评论中所说,为了加快代码的速度,您可以使用它。尝试以下代码

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)

您可以将代码的速度提高2倍。在for循环中,您只能检查奇数,因为只有偶数素数是2