1
int logarithmCeiling(int x) {
    int power = 1;
    int count = 0;

    while (power < x) {
        power = 2 *power;
        count = count +1;
    }
    return count;
}

The code above is meant to be a method in Java for computing and returning the lower logarithm of a given positive integer using a while-loop. How would I provide an invariant for the loop above? i.e. that holds before it starts, every time the loop body ends, and the negation of the loop condition.

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
Paradox
  • 353
  • 3
  • 9
  • 14

4 Answers4

1

power always equals 2^count at the beginning and end of the loop. For the negation, when the loop is over, x <= power = 2^count.

astay13
  • 6,857
  • 10
  • 41
  • 56
  • While correct, this is not as strict as you can be for the post-condition. 5 <= 1024 = 2^10 Could be an instance of this, but 10 obviuosly wouldn't be the correct log. Of course, the method really is partially correct and a stronger postcondition could be shown – b.buchhold May 23 '11 at 16:14
0

There's a simple relationship between the value of power and the value of count: power=2count. This holds at the start and end of the loop, but not at certain places in in the loop body.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Look for variables or conditions that are always true. Each iteration count is always incremented by 1, and power is always multiplied by 2. Since the purpose of the function is to find the lower logarithm of the given argument, you could say the loop invariant is that count is always equal to the logarithm of x, rounded down. Another one would be that count is always equal to the logarithm of power.

Ryan
  • 712
  • 7
  • 21
0

I guess you are looking for an invariant which is suited to proof partial correctness of the method? Otherwise "true" or "false" are always invariants. I'd go with something like this:

I: {(power <= x) AND (power == 2 ^ count) AND (x > 2 ^ count -1) AND (power >= 1)}

The r.h.s. can be implied from your initializations and helps ensureing the lower bound for x. Together with the negated loop condition you can later imply.

{(x <= 2 ^ count) AND (x > 2 ^ (count -1))}

which is exactly what you want for showing partial correctness of the whole function.

b.buchhold
  • 3,837
  • 2
  • 24
  • 33