theSecretCoder
theSecretCoder

Reputation: 713

How to calculate the modulus in another way than using a while loop?

public static int compareAndReturn(int a, int b)
{
    while (a > b)
    {
        a -= b;
    }
    return a;
}

Upvotes: 2

Views: 80

Answers (2)

Eran
Eran

Reputation: 393936

You should eliminate the loop, since a can be much larger than b, which would result in many iterations of the loop.

public static int compareAndReturn(int a, int b) { 
    if (a <= b)
        return a;
    else if a % b == 0
        return b;
    else
        return a - (a/b) * b;
}

or

public static int compareAndReturn(int a, int b) { 
    return (a <= b) ? a : a % b == 0 ? b : a - (a/b) * b;
}

or (based on Tim's answer)

public static int compareAndReturn(int a, int b) { 
    return a % b == 0 ? b : a % b;
}

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521997

I believe your code snippet is just a manual way of computing the modulus, or remainder, when dividing a by b. Your method could be rewritten as:

public static int compareAndReturn(int a, int b) {
    return a % b;
}

Upvotes: 5

Related Questions