Search code examples
javainvariantsloop-invariant

how to find loop invariant java


I'm trying to find the invariant of the loops (for example in the following code) I really don't know how to find an invariant in general. can anyone help me with how to find an invariant and also help me to find it for the following code? thanks

public static int div(int a, int b)
{
   int q = 0;
   while(a >= b)
   {
      a -= b;
      q++;
   }

   return q;
}

Solution

  • First thing to note about loop invariants is that there are many of them. Some of them are more useful, while some are less useful. Since invariants are used in proving correctness of programs, choosing an invariant depends on what you are trying to prove.

    For example, q >= 0 is an invariant of the loop. If you want to prove that the function returns a positive number, this is all you need. If you want to prove something more complex, you need a different invariant.

    Since parameters in Java are passed by value, and because the program modifies values of the parameter a, let's use a0 to denote the initial values of the a parameter. Now you can write the following invariant expression:

    a == a0 - (b * q)
    

    You come up with this invariant by observing that each time that q is increased, a is also decreased by b. So a0 is decreased by b exactly q times on each iteration of the loop.

    This invariant can be used to prove that the loop produces q == a0 / b, and that the ending value of a is equal to a0 % b.