I’ve tried making a simple Greatest Common Denominator code but output differs depending on where I use return.
First is the code that works as intendent. By using else statement, as far as I understand return runs only once and code terminates.
function GCD(a, b, r)
n::Int64 = max(a, b)
k::Int64 = min(a, b)
z = n-k
println("z is $z, n is $n, k is $k, Round $r")
if ((z>=1) | (k<=1))
println("GTD not yet Found!")
GCD(z, k, r+1)
else
println("GTD is $k")
return k, r
end
#println("GTD is $k")
#return k, r
end
The output for this code using GCD(32, 12) is as expected (4, 4).
This is the full output, if needed:
z is 20, n is 32, k is 12, Round 0
GTD not yet Found!
z is 8, n is 20, k is 12, Round 1
GTD not yet Found!
z is 4, n is 12, k is 8, Round 2
GTD not yet Found!
z is 4, n is 8, k is 4, Round 3
GTD not yet Found!
z is 0, n is 4, k is 4, Round 4
GTD is 4
(4, 4)
Now, if we remove else statement and use the code in the comment at the bottom, like that:
function GCD(a, b, r)
n::Int64 = max(a, b)
k::Int64 = min(a, b)
z = n-k
println("z is $z, n is $n, k is $k, Round $r")
if ((z>=1) | (k<=1))
println("GTD not yet Found!")
GCD(z, k, r+1)
end
println("GTD is $k")
return k, r
end
Now, code returns
z is 20, n is 32, k is 12, Round 0
GTD not yet Found!
z is 8, n is 20, k is 12, Round 1
GTD not yet Found!
z is 4, n is 12, k is 8, Round 2
GTD not yet Found!
z is 4, n is 8, k is 4, Round 3
GTD not yet Found!
z is 0, n is 4, k is 4, Round 4
GTD is 4
GTD is 4
GTD is 8
GTD is 12
GTD is 12
(12, 0)
What I don’t understand is why the last println statement repeats itself, its as if the code is running in backward, or running the part of the code that hasn’t ran in previous rounds. Why is that?
Thank you for your answer!