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 count the number of integers that are divisible by k in an array.
Algorithm: divisibleByK (a, k)
Input: array a of n size, number to be divisible by k
Output: number of numbers divisible by k
int count = 0;
for i <- 0 to n do
if (check(a[i],k) = true)
count = count + 1
return count;
Algorithm: Check (a[i], k)
Input: specific number in array a, number to be divisible by k
Output: boolean of true or false
if(a[i] % k == 0) then
return true;
else
return false;
How would one prove that this is correct? Thanks
In this case I would interpret “inductively” as “induction over the number of iterations”.
To do this we first establish a so called loop-invariant. In this case the loop invariant is:
countstores the number of numbers divisible bykwith index lower thani.This invariant holds upon loop-entry, and ensures that after the loop (when
i = n)countholds the number of values divisible bykin whole array.The induction looks like this:
Base case: The loop invariant holds upon loop entry (after 0 iterations)
Since
iequals 0, no elements have index lower thani. Therefore no elements with index less thaniare divisible byk. Thus, sincecountequals 0 the invariant holds.Induction hypothesis: We assume that the invariant holds at the top of the loop.
Inductive step: We show that the invariant holds at the bottom of the loop body.
After the body has been executed,
ihas been incremented by one. For the loop invariant to hold at the end of the loop,countmust have been adjusted accordingly.Since there is now one more element (
a[i]) which has an index less than (the new)i,countshould have been incremented by one if (and only if)a[i]is divisible byk, which is precisely what the if-statement ensures.Thus the loop invariant holds also after the body has been executed.
Qed.
In Hoare-logic it’s proved (formally) like this (rewriting it as a while-loop for clarity):
Where
I(the invariant) is:count= ∑x < i 1 ifa[x]∣k, 0 otherwise.(For any two consecutive assertion lines (
{...}) there is a proof-obligation (first assertion must imply the next) which I leave as an exercise for the reader 😉