Exp(n)
If n = 0
Return 1
End If
If n%2==0
temp = Exp(n/2)
Return temp × temp
Else //n is odd
temp = Exp((n−1)/2)
Return temp × temp × 2
End if
how can i prove by strong induction in n that for all n ≥ 1, the number of multiplications made by Exp (n) is ≤ 2 log2 n.
ps: Exp(n) = 2^n
A simple way is to use strong induction.
First, prove that
Exp(0)
terminates and returns2^0
.Let N be some arbitrary even nonnegative number.
Assume the function
Exp
correctly calculates and returns2^n
for everyn
in [0, N].Under this assumption, prove that
Exp(N+1)
andExp(N+2)
both terminate and correctly return2^(N+1)
and2^(N+2)
.You're done! By induction it follows that for any nonnegative
N
,Exp(N)
correctly returns2^N
.PS: Note that in this post,
2^N
means "two to the power of N" and not "bitwise xor of the binary representations of 2 and N".