Próbuję znaleźć największy wspólny czynnik.Python podczas pętli, operator i (&) nie działa
Napisałem zły (operujący intensywnie) algorytm, który zmniejsza niższą wartość o jeden, sprawdza za pomocą%, czy równomiernie dzieli zarówno licznik, jak i mianownik, jeśli tak, to wychodzi z programu. Jednak moja pętla while nie używa operatora i, a więc gdy licznik jest podzielny, zatrzymuje się, nawet jeśli nie jest poprawną odpowiedzią.
Numery używam są 54 i 42, prawidłowa NWD (największy wspólny mianownik) to 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
Odpowiedź jestem coraz to 27, który mówi mi, po osiągnięciu 27 i może podzielić 54/27 równomiernie, zatrzymuje się. Wszelkie przemyślenia na temat używania i operatora w pętli while w python?
Dzięki!
Dzięki za wiadomość próbowałem użyć słowa kluczowego i, ale nadal mam 27, czy otrzymujesz taki sam wynik? – Blakedallen
@Blakedallen: Spróbuj użyć 'lub'. –
Masz rację, to jest bardzo nieefektywne! Uważam, że algorytm Euclida jest znacznie lepszy. – Blakedallen