2017-11-07 22 views
2

私はnに乗、番目の保番号(数字、元の番号(例:625 = 390625、390625パーセント1000年= 625で終わりを解決するためのプログラムを書きました)。貧しいコード、初年度コンプサイのため申し訳ありません長い実行時間

import time 
def green(n): 
    start_time = time.time() 
    f = 3 
    if n==1: 
    return 1 
    elif n==2: 
    return 5 
    elif n==3: 
    return 6 
    n1 = "5" 
    n2 = "6" 
    tempn2 = "0" 
    tempn1 = "0" 
    x = 1 
    while f!=n+1: 
    if int(n1) > int(n2): 
     tempn2 = str(x) + n2 
     while int(pow(int(tempn2), 2, 10**(len(tempn2)))) != int(tempn2): 
     tempn2 = str(x) + n2 
     x+=1 
     x=1 
     f+=1 
     n2 = tempn2 
     if f==n+1: 
     break 
    else: 
     tempn1 = str(x) + n1 
     while int(pow(int(tempn1), 2, 10**len(tempn1))) != int(tempn1): 
     tempn1 = str(x) + n1 
     x+=1 
     x=1 
     f+=1 
     n1 = tempn1 
    print("--- %s seconds ---" % (time.time() - start_time)) 
    return min(int(n1), int(n2)) 

Program Runtime vs. Input

私はで目5000 が必要12秒未満の実行時間にする。現在のコードは約45秒かかります。

+0

pow関数を使用して、10のべき乗を計算して計算を高速化できます。 'pow(n、2、10)'はn平方根の最後の桁を返します –

+0

@DanielGee残念なことに実行時の変更はありませんが、コードを凝縮しました。 – Rxted

+1

この質問は、https://codereview.stackexchange.com – ti7

答えて

0
  • 意味のある変数名を使用してください。アルファベットのスープは読みにくいです。
  • 数式は整数で行い、文字列との変換は行いません。 1桁の数字で始まるので、を認識します。文字列の連結や整数への変換の代わりに、直接数値を作るだけです。

コード

for f in range(1, n//2): 
    ten_power = next_power # Keep track of length in digits 
    next_power *= 10 

    # "old5" is the previous automorphic number ending in 5 
    for digit in range(9, 0, -1): 
     new5 = old5 + digit * ten_power 
     new5sq = new5*new5 
     if new5sq % next_power == new5: 
      # you found the number 
      old5 = new5 
      break 

は、あなたの既存のコードにこれらの事を働くことはできますか?外側のforループは異なる制御を持つことに注意してください。 を見つけるn//2の5と6の数字はです。あなたが小さい方を気にする唯一の時間は、奇数nの最終的な繰り返しです。

これは、green(5000)を1.5秒で検出しました。

関連する問題