[英]I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors?
[英]Python: Find the two prime factors of a number. how to make this code more efficiency?
为了加快您的代码速度,您可以使用Fermat 的分解方法,正如 @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
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.