How do I write this code in Java?
def gcd(a, b):
"""
Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
It seems I can't do while (b) {
in Java because of Type mismatch
error. It seems I also can't do the line a, b = b, a%b
exactly in Java as well.
public static int gcd(int a, int b) {
int temp;
while(b != 0) {
temp = a;
a = b;
b = temp % b;
}
return a;
}
Java expects the condition of the while
to be a boolean, not an int
.
The a, b = b, a%b
syntax will not work in Java. You need to do the assignments individually.
So you can set a = b
, and then set b = a % b
. I used a temp variable to hold the old value of a
so that I can compute a % b
(before I overwrote a
with a = b
).