![](/img/trans.png)
[英]Kattis 'Digits' question: Why does my first set of code exceed time limit, but my second set does not?
[英]Why does the longer code does not exceed the time limit whereas the shorter exceeds the time limit?
這是一個簡單的代碼,用於計算兩個數字的公因數。 如何第一個代碼不超過並列限制而第二個代碼超過時間限制。 第一的
from math import sqrt
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def commDiv(a, b):
# find GCD of a, b
n = gcd(a, b)
# Count divisors of n
result = 0
for i in range(1,int(sqrt(n))+1):
# if i is a factor of n
if n % i == 0:
# check if divisors are equal
if n/i == i:
result += 1
else:
result += 2
return result
if __name__ == "__main__":
a , b = map(int,input().split())
print(commDiv(a, b))
第二
a , b = map(int,input().split())
if a>b:
small = b
big = a
else:
small = a
big = b
c = 0
for i in range(1,small+1):
if small%i == 0 and big%i == 0:
c = c + 1
print(c)
CPU 周期數(執行速度)更多地取決於算法而不是代碼長度。
在這種特殊情況下,您的第二個解決方案有一個重復small
次數的循環。 因此,比方說,對 (1200, 700) 它將重復 700 次。
您的第一個解決方案從找到兩個數字的 GCD 開始。 “大多數情況下”它將比任何一個數字都小得多(除非a
可以被b
整除,反之亦然)。 然后它只重復sqrt(gcd)
次,最終迭代次數更少。 對於同一對,GCD 為 100,因此循環將重復sqrt(100) == 10
次。 十對七百。
即使在最壞的情況下, a
可以被b
整除,例如 (300000, 10000),您的FIRST解決方案將迭代sqrt(10000) == 100
次,而您的SECOND將迭代 10000 次。
編輯:需要注意的是,GCD 計算本身確實占用了幾個 CPU 周期,但它的實現方式會大步遞歸,對總時間的影響較小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.