Home > Back-end >  Find GCD of 2 numbers
Find GCD of 2 numbers

Time:09-17

What is wrong here?

The loop conditions should be fulfilled but the program is not entering the loop.

a=100
b=55
c = min(a,b)
while (a % c !=0 // b % c != 0):
    c = c - 1
    gcd = c
print(gcd)

CodePudding user response:

// is the floor division operator. You need to use or for the logical OR function. Here is a simple article on basic Python operators.

a=100
b=55
c = min(a,b)
while (a % c !=0) or (b % c != 0):
    c = c - 1
    gcd = c
print(gcd) # prints 5

CodePudding user response:

Not strictly what you're asking about, but the far more efficient way to compute the gcd is with the Euclidean algorithm. Also, gcd = c does not need to be inside the while loop.

Here's some alternative code.

a = 100
b = 55

while b != 0:
    a, b = b, a % b
gcd = a
print(gcd)
  • Related