Domanda

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.

È stato utile?

Soluzione

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).

Altri suggerimenti

Do you really need a while? It can be as simple as-

public static int gcd(int a, int b) {

   if (b == 0) return a;

   return gcd(b, a % b);

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top