2012-05-26 7 views
7

Sto cercando di trovare il più grande fattore comune.Python While Loop, l'operatore e (&) non funziona

Ho scritto un algoritmo errato (operazione intensiva) che decrementa il valore più basso di uno, controlla utilizzando% per vedere se divide equamente sia il numeratore che il denominatore, se lo fa, esce dal programma. Tuttavia, il mio ciclo while non usa l'operatore e, quindi, una volta che il numeratore è divisibile, si ferma, anche se non è la risposta corretta.

I numeri sto usando sono 54 e 42, il corretto MCD (massimo comune denominatore) è 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 

La risposta che sto ottenendo è 27, che mi dice una volta che raggiunge il 27 e può dividere 54/27 in modo uniforme, si ferma. Qualche idea su come usare un operatore e in un ciclo while in python?

Grazie!

risposta

15

Si deve usare la parola and al posto del bit a bit e gestore &:

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

Questo è anche lo stesso:

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

noti che & e and darà lo stesso risultato in il primo caso, ma non il secondo.

Il problema è che si desidera utilizzare or anziché and. Anche il tuo algoritmo è altamente inefficiente. Ci sono better ways to calculate the GCD.

+0

Grazie per l'input, ho provato a utilizzare la parola chiave e, ma ho ancora 27, ottieni lo stesso risultato? – Blakedallen

+0

@ Blakedallen: prova a usare 'o'. –

+0

Hai ragione è molto inefficiente! Credo che l'algoritmo di Euclide sia molto meglio. – Blakedallen

0

Utilizzare la parola chiave and. & è un bit per bit e operatore.