Search code examples
javafunctionmaxmin

how does this (max) function work using while loop?


I had a homework to use functions in java to get the maximum number in a set of 3 numbers and this is what I came up with:

public static int max(int b, int a ,int d) {
    int o =0;
    while (b!=0 && a!=0 && d!=0)
    {
        b++;
        a++;
        d++;
        o--;
    }
    return o;
}

The thing is if it is given 3 numbers it will work but I do not understand how it works.


Solution

  • Ok, so what it's doing is increasing all three variables b, a, and d, until any of them equals zero. It keeps a count o of the number of times it's looped (i.e. the number of iterations necessary for any variable to hit zero), except negative.

    If b, a, and d are negative, then they would approach 0 relatively quickly, and o would come out negative - but that's not what's happening is it? You're putting in positive numbers, and getting out a positive result.

    That's because this solution relies on integer overflow. When b, a, or d reaches the integer max value of 2147483647, it wraps back around to -2147483648, and keeps counting back up towards zero. Meanwhile, o does the same thing in the opposite direction, wrapping the other direction. The math works out such that, when b, a, or d reaches zero, then o reaches the exact value that b, a, or d started at.

    (for negative numbers, the convergence happens much more quickly - but you might be in for a shock if you put both a negative and a positive number into this function. It'll tell you that the negative number is larger than the positive number!)


    Now that you understand how it works, you also understand why this is a terrible solution to this problem. It will run for much, much longer than necessary in order to get a result (unless the input is negative, in which case it will only run for a little longer than necessary).

    The more reasonable common-sense implementation would look like this:

    public static int max(int b, int a ,int d) {
        if (a >= b && a >= d) {
            return a;
        } else if (b >= a && b >= d) {
            return b;
        } else {
            return d;
        }
    }
    

    which incorpoates at most four operations, no matter how large a, b, or d is.