I am trying to understand Euclid's Algorithm for finding greatest common divisors and am having difficulty with this code, specifically the multivariable assignment.
def greatest_common_factor(u, v)
u, v = u.abs, v.abs
puts(u % v)
while v > 0
u, v = v, u % v
end
u
end
I assumed 'u' would be assigned first, then v, but writing it more explicitly broke the algorithm.
u = v
v = u % v
When you write this:
u = v
v = u % v
I think it's just something like this:
u = v
v = v % v # u == v, this will make v to be 0, so break it down
And I will try to answer the multiple variable assignment question. This is my test code:
a = 1
b = 2
a, b = 3, a # after this, a == 3, b == 1
You can see that, it's just like a, b = [3, a]
, you will evaluate [3, a]
part first. And here comes the Ripper
analyse:
[:program,
[[:massign,
[[:@ident, "a", [1, 0]], [:@ident, "b", [1, 2]]],
[:mrhs_new_from_args,
[[:@int, "3", [1, 4]]],
[:var_ref, [:@ident, "a", [1, 6]]]]]]]
You will see that :mrhs_new_from_args
will be evaluated first as I said above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With