While loop

# Greatest Common Divisor

# Two numbers
m = int(input("Enter the number, m: "))
n = int(input("Enter the number, n: "))

#the divisor

d = int (input("Enter the divisor, d: "))

while m % d != 0 and n % d != 0:
    d = d - 1

print ("the greatest common divisor" , d, )

This part is not working

If you want the GCD why are you asking the user to input it?
There is already a method for GCD in the math module, but if you really want to do it yourself look up the Euclidean algorithm… you don’t need or want the user to input the divisor.

thank you for the information, will surely check out, but here in this method l just wanted to pick a number smaller than m and n, and keep reducing it by one until it divides them, which will make them the greatest common divisor, if you can help me with this code

Your logic to solve this issue is flawed, you don’t WANT or NEED the user to input a starting divisor.

The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number.
Not only do you not need the user to input d, it wont help.

If you looked at the wiki for the algorithm I posted for you, there are multiple examples of pseudocode showing how it could be implemented.

For example:

# Greatest Common Divisor

# Two numbers
m = int(input("Enter the number, m: "))
n = int(input("Enter the number, n: "))

def gcd(x, y):
    while x != y:
        if x > y:
            x = x - y
            y = y - x
    return x

The above example is a subtraction based version. (The wiki goes over WHY this works)
Note: This function only works for positive integers.

I highly suggest you actually read over the wiki.

1 Like

# Compute the greatest common divisor of two positive integers using a while loop.
# Read two positive integers from the user
n = int(input("Enter a positive integer: "))
m = int(input("Enter a positive integer: "))
# Initialize d to the smaller of n and m
d = min(n, m)
# Use a while loop to find the greatest common divisor of n and m
while n % d != 0 or m % d != 0:
# Report the result
print("The greatest common divisor of", n, "and", m, "is", d)

This is a solution l found, it also works

1 Like

Yep, your code will do the same thing as my function. I just used if statements to check which number was larger, instead of using min().

Do you understand why your new code works compared to your old code?

yes, l understand now


1 Like