int fact(int n)
{
if(n<=1) return(1);
else return(n*fact(n-1));
}
The proof works as follows:
(Basis) The program calculates n! properly for n=0 or n=1 since
0!=1!=1.
(Induction) Suppose that n! is representable by ordinary int variables
and that for k<n fact(k) returns k! (Not that since n! is
increasing,
if n is representable, so isk! for k<n.)
Then fact(n) returns n*fact(n-1) and since n-1<n, fact(n-1)=(n-1)!
so we see that fact(n) returns n*(n-1)!=n*(n-1)*(n-2)*...*1 (by the
definition
of factorial) and this is, in fact,
n!. QED (QED is an acronym for latin Quid Errat Demonstratum which
means, essentially, it is properly demonstrated. Mathematicians love
using
it at the end of proofs. So do computer scientists.)
Let us try another. Note that Fn , the nth Fibonnacci number is defined by the recurrence relationship F0=F1=1 and Fn=Fn-1+Fn-2 . Suppose the following is a program to compute the nth Fibonnacci number:
int Fib(int n)
{
if(n<=1) return(1);
else
return(Fib(n-1)+Fib(n-2));
}
Let us prove that Fib(n) returns Fn when n is nonnegative and such that Fn can be represented in an int.
(Basis) True for n=0 or n=1 since in both cases it returns 1 and F0=F1=1.
(Induction) Suppose n is such that Fn can be represented
in an int and n>1. Inductively suppose that for k<n, the function
Fib
works correctly - i.e., Fib(k)=Fk for k<n. Then let us
compute
Fib(n). It will return Fib(n-1)+Fib(n-2) and by the inductive
hypothesis,
this is Fn-1+Fn-2 since n-1<n and n-2<n.
But,
by definition, Fn=Fn-1+Fn-2 so Fib(n)
returns Fn and we have shown the result by induction. QED