Python Podczas gdy pętla, operator i (i) nie działa
Próbuję znaleźć największy wspólny czynnik.
Napisałem zły (intensywnie działający) algorytm, który zmniejsza 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ę, mimo że nie jest to poprawna odpowiedź.
Liczby, których używam, to 54 i 42, prawidłowy GCD (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ź, którą otrzymuję, to 27, która mówi mi, że gdy osiągnie 27 i może równomiernie podzielić 54/27, przestaje. Jakieś przemyślenia na temat używania operatora i operatora w pętli while w pythonie?
Dzięki!