I don\'t really understand how one uses proof by induction on psuedocode. It doesn\'t seem to work the same way as using it on mathematical equations.
I\'m trying to cou
We prove correctness by induction on n
, the number of elements in the array. Your range is wrong, it should either be 0 to n-1 or 1 to n, but not 0 to n. We'll assume 1 to n.
In the case of n=0 (base case), we simply go through the algorithm manually. The counter
is initiated with value 0, the loop doesn't iterate, and we return the value of counter, which as we said, was 0. That's correct.
We can do a second base case (although it's unnecessary, just like in regular maths). n=1. The counter is initialised with 0. The loop makes one pass, in which i
takes value 1, and we increment counter
iff the first value in a
is divisible by k
(which is true because of the obvious correctness of the Check
algorithm).
Therefore we return 0 if a[1]
was not divisible by k
, and otherwise we return 1. This case also works out.
The induction is simple. We assume correctness for n-1 and will prove for n (again, just like in regular maths). To be properly formal, we note that counter
holds the correct value that we return by the end of the last iteration in the loop.
By our assumption, we know that after n-1 iterations counter
holds the correct value regarding the first n-1 values in the array. We invoke the base case of n=1 to prove that it will add 1 to this value iff the last element is divisible by k, and therefore the final value will be the correct value for n.
QED.
You just have to know what variable to perform the induction on. Usually the input size is most helpful. Also, sometimes you need to assume correctness for all naturals less than n, sometimes just n-1. Again, just like regular maths.