2012-05-26 14 views
7

私は最大の共通要因を見つけようとしています。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で使用するかについての考えはありますか?

ありがとうございます!

答えて

15

あなたが代わりにビット単位の演算子&のキーワードandを使用する必要があります。

while (v % d != 0) and (u % d != 0): 

これも同じである:&andがで同じ結果を与えることを

while (v % d) and (u % d): 

は注意最初のケースではなく、2番目のケースでは発生しません。

andの代わりにorを使用することが問題です。また、あなたのアルゴリズムは非常に非効率です。 better ways to calculate the GCDがあります。

+0

入力いただきありがとうございます。私はキーワードandを使ってみましたが、まだ27がありますが、同じ結果が得られていますか? – Blakedallen

+0

@Blakedallen: 'または'を使って試してみてください。 –

+0

あなたはこれが非常に効率的ではないという正しいです!私はユークリッドのアルゴリズムがはるかに優れていると信じています。 – Blakedallen

0

キーワードandを使用してください。 &はビット単位の演算子です。

関連する問題