簡體   English   中英

Python:找出一個數的兩個質因數。 如何讓這段代碼更有效率?

[英]Python: Find the two prime factors of a number. how to make this code more 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 秒(超出時間限制);

有什么建議嗎? 謝謝!

為了加快您的代碼速度,您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM