Search code examples
pythongreatest-common-divisor

greatest common divisor (python)


I'm trying to get my code to print out my greatest common devisor. Technically my code should work, but it always goes one step firther until x = 0 even though it should print x = gcd Everything you see in the code kind of has to stay as it is structure base, due to the assignement of my school. Meaning I have to print out x and have a while loop with r != 0 and so on... Whatever you most likely know how to fix it without me overexplaining my code xD

def ggt2(x, y):
    r = 1
    while r != 0:       #I have to use a while loop
        if x < y:
            r = x % y
            x = y
            y = r
            print(x)    #here it prints nothing at all
        elif x > y:
            r = x % y
            y = x
            x = r
            print(x)    #here it prints x = 0
x = input()
y = input()
ggt2(int(x), int(y))

EDIT: Here is the pseudo code we were given. This is basically the structure I have to follow. We were also told to switch x <-> y if x < y.

GCD :var X,Y,R: int;
input X,Y;
R:=1;
while R ≠ 0 do
R:=X mod Y; X:=Y; Y:=R;
od;
output X.

Solution

  • def ggt2(a, b):
        while b != 0:
            t = b
            b = a % b
            a = t
        return a if a != 0 else None
    
    a = int(input("Enter a: "))
    b = int(input("Enter b: "))
    print("Their GCD is: "+str(ggt2(a,b)))
    

    This code was converted to Python from the pseudocode on Wikipedia, with minor changes made.

    There are some things wrong with your code. Here is your give pseudocode:

    GCD :var X,Y,R: int;
    input X,Y;
    R:=1;
    while R ≠ 0 do
    R:=X mod Y; X:=Y; Y:=R;
    od;
    output X.
    

    What this says is:

    1. Start GCD
    2. create variables X, Y, and R of type int each
    3. Input a value to X and Y
    4. Set R to 1
    5. While R is not equal to 0 do:
    6. (in loop of 5) set R to X % Y (the remainder of X and Y)
    7. (in loop of 5) set X to Y
    8. (in loop of 5) set Y to R
    9. End of loop started on statement 5 iteration
    10. Print out X

    This pseudocode converted to Python would be:

    def GCD():
        X = int(input("Enter X: "))
        Y = int(input("Enter Y: "))
        R = 1
        while R != 0:
            R = X % Y
            X = Y
            Y = R
        print(X)
    
    GCD()
    

    Try to figure out how this works, and tell me in the comments if it worked for you!