Let P(i)
be the statement:
exp(m, i)
computes mi for any integer m
For the base case, it is clear that P(0)
is true as we have exp(m, 0) = 1 = m^0
.
For the inductive step, we assume that P(0), P(1), ..., P(k-1)
are all true, and we claim that P(k)
is also true. We have to consider the following three cases:
1.) If k = 1
, then P(1)
is clearly true as we have exp(m, 1) = m = m^1
;
2.) If k > 1
and k % 2 == 0
, then by the definition of exp
we have:
exp(m, k) = exp(m * m, k / 2)
By the induction hypothesis, we have exp(m * m, k / 2) = (m * m)^(k / 2) = m^k
, hence P(k)
is true in this case.
3.) If k > 1
and k % 2 == 1
, then by the definition of exp
we have:
exp(m, k) = exp(m * m, k / 2) * m
By the induction hypothesis, we have exp(m * m, k / 2) = (m * m)^(k / 2)
. Since k % 2 == 1
, we have k / 2 = (k - 1) / 2
. Hence we have:
exp(m * m, k / 2) = (m * m)^(k / 2) = (m * m)^((k-1) / 2) = m^(k-1)
Thus:
exp(m, k) = exp(m * m, k / 2) * m = m^k
So P(k)
is also true in this case.