私は最大の共通要因を見つけようとしています。Python Whileループで、(&)演算子が機能しない
私は、低い値を1減らし、%を使って分子と分母の両方を均等に分割するかどうかを調べ、プログラムを終了するかどうかを調べるアルゴリズムを書いています。しかし、私のwhileループはand演算子を使用していないので、一度分子が割り切れると、正解ではなくても停止します。私が使用しています
番号は54と42です、正しいGCD(最大公約数)が6
#heres a simple algorithm to find the greatest common denominator:
iterations = 0; #used to calculate number of times while loop is executed
u = 54; v= 42; d = v-1; #u is the numerator, v is the denominator, d is the number decremented by one
while ((v % d !=0) & (u % d != 0)): #while both numerator AND denominator cannot be evenly divided by the decremented number
d -= 1 #decrement the number by one
print d #print the number decremented
iterations +=1 #add 1 to the count of iterations in while loop
print "the gcd is " +str(d) #should be 6 when the number can evenly divide both
print "the number of iterations was " +str(iterations) #display times it took algorithm to complete
である私が取得しています答えは、それが27に到達して分割することができたら、私に語った、27です54/27が均等に停止します。どのようにして、演算子をwhileループでPythonで使用するかについての考えはありますか?
ありがとうございます!
入力いただきありがとうございます。私はキーワードandを使ってみましたが、まだ27がありますが、同じ結果が得られていますか? – Blakedallen
@Blakedallen: 'または'を使って試してみてください。 –
あなたはこれが非常に効率的ではないという正しいです!私はユークリッドのアルゴリズムがはるかに優れていると信じています。 – Blakedallen