-1

the algorithm is intended to compute m^n for any positive integer m, n. How do i show the correctness of this algorithm through induction on n.

long exp(long m, int n) {

if(n == 0) return 1;

if(n == 1) return m;

if(n % 2 == 0) return exp(m*m, n/2); 

else return exp(m*m, n/2) * m;

}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user1505521
  • 231
  • 1
  • 2
  • 12

1 Answers1

0

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.

chiwangc
  • 3,566
  • 16
  • 26
  • 32