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.
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:
GCD
X
, Y
, and R
of type int
eachX
and Y
R
to 1R
is not equal to 0
do:R
to X
% Y
(the remainder of X
and Y
)X
to Y
Y
to R
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!