Python Forum
Why is this giving me an infinite loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why is this giving me an infinite loop?
#1
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"
Reply
#2
(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.
Recommended Tutorials:
Reply
#3
Also, what was wrong with line 10? I don't understand why I had to change that.
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
I'm new to programming, I don't get your code.
You can solve it with Euclidean algorithm.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Infinite loop Danado 4 2,351 Aug-16-2021, 05:56 PM
Last Post: deanhystad
  Help with while loop creating an infinite loop. FWendeburg 3 3,027 Jan-30-2019, 08:28 PM
Last Post: FWendeburg
  Infinite loop/ only half working anclark686 5 4,725 Sep-09-2018, 07:31 AM
Last Post: buran
  Another infinite loop wlsa 7 4,643 Jul-20-2018, 12:04 AM
Last Post: wlsa
  How to stop an infinite loop in spyder if it's currently running? wlsa 3 24,682 Jun-30-2018, 03:27 AM
Last Post: ichabod801
  Infinite loop Truman 9 9,073 Jan-19-2018, 11:25 PM
Last Post: j.crater

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020