2016-12-13 3 views
0

私はプロジェクトのユーラー問題5をやっています。私のループが見つけた最初の番号が必要です(最小であるためです)。最初の結果が見つかるとループします。ブレークを使用しようとしましたが、動作しません。ここに私のコードです:最初に見つかった答えを出力してループを終了する簡単な方法

"""2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. 

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?""" 


dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime; 
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime 

for x in range(20, 999999999, 20): # step has to be 20 so the number can be divisible by 20 
    if all(x % n == 0 for n in dividers): 
     print(x) 

結果:

/usr/bin/python3.5 "/home/michal/Desktop/Project Euler/Problem5.py" 
232792560 
465585120 
698377680 
931170240 

Process finished with exit code 0 

は休憩と試みたが、それだけで(ちょうど私のプリントを移動しなければならなかった

dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime; 
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime 

for x in range(20, 999999999, 20): # step has to be 20 so the number can be divisible by 20 
    if all(x % n == 0 for n in dividers): 
     break 
    print(x) 
+1

'break'はあなたが望むものを正確に行うべきです。あなたはそれをどのように使ってみましたか? – Hamms

+0

あなたのインデントを見ることができるように私のコードをコメントに書式設定する方法はありません...私のメインポストを編集するつもりです – doublemc

+0

'break'の有無にかかわらずあなたの例のインデントの違いを注意深く見て、 Pythonで動作します。 – Hamms

答えて

2

20で割り切れるすべての数を出力しますx)ルークが述べたforループの外側。ここで コード取り組んでいる:

dividers = [11, 13, 14, 16, 17, 18, 19, 20] # if it divides by 20 we can cross out 2, 4, 5, 10; 19 is prime; 
# if it divides by 18 we can remove 3, 6, 9; 17 is prime; if by 16 then 8; if by 14 then 7; 13 is prime; 11 is prime 

for x in range(20, 999999999, 20): # step has to be 20 so the number can be divisible by 20 
    if all(x % n == 0 for n in dividers): 
     break 
print(x) 
0

を私は関数にそれを行うことをお勧めしたい:あなたが通過するとき

def project_Euler_Problem5(dividers): 
    for x in range(dividers[:-1], 999999999, dividers[:-1]): 
     if all(x % n == 0 for n in dividers): 
      return x 

それは注文あなたの他のオイラーソリューションのすべてを作るの付加的な利点を持っていると思いますそれらを(そして古いものを保つ)。

おもしろい事実:答えの最初の部分に達する前に答えが見つからないので、20の代わりに2520から開始することもできます。

編集:大きな範囲(20〜999999999など)を作成する場合は、コードを少し速く実行するようにxrange()を使用することをおすすめします(特にこれを一貫して行う場合)。

編集:この機能はコードをパッケージ化するだけです。何らかの理由でそれを任意の数の除数に抽象化したいのであれば、それを反映するように変更したいと思います。

関連する問題