def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
r=1
GCD=1
smaller=b
if a>b is True:
b=smaller
if b>a is True:
a=smaller
while smaller >=r:
if a%r==0 and b%r==0:
r=GCD
r+=1
else:
r+=1
print(GCD)
gcdIter(2,4)
I know this propably isn't the most efficient way of finding the greatest common denominator, but I don't understand how I'm getting an infinite loop, from what I can tell I have made "r" continually increase by 1 until it is greater than the smallest given integer.
I figured it out, I changed line 10 to "smaller=1"
(Jul-13-2018, 12:23 AM)wlsa Wrote: [ -> ]I figured it out, I changed line 10 to "smaller=1"
also the
is True
is redundant here. The result of
X>Y
returns True or False.
Also, what was wrong with line 10? I don't understand why I had to change that.
Because your code doesn't work. Walk through the original code. Smaller gets set to b (4). Since b > a, a gets set to smaller (4). First loop smaller >= r (4 >= 1). The conditional is triggered, because anything % 1 = 0. So r is set to GCD (1), and then one is added to it. Second smaller >= r (4 >= 2). The conditional is triggered again, because both a and b are 4 and 4 % 2 == 0. So r is set to GCD (still 1) and one is added to it. Third loop (and every loop thereafter) 4 >= 2. r is always 2 when the loop is checked.
By changing smaller = 1, on the second loop you get 1 >= 2, which is False. So you get out of the infinite loop. but that doesn't mean the answer you're getting is correct.
I'm new to programming, I don't get your code.
You can solve it with Euclidean algorithm.