Question 1-2

Consider the following method to compute the greatest common denominator of two numbers.

public static int sqrt(int n) {
    int x = 0;
    int d = n;
    while(d > 0) {
        if((x + d) * (x + d) <= n) x += d;
        d /= 2;
    }
    return x;
}
Say we call sqrt(32). Show how the values of x and d change as the computer continues through the method.
x
d

Solution

x  0  4  5
d 32 16  8  4  2  1  0

Back to Review for Quiz 1