// expon: fast exponentiation
int expon(int a, int b) {
int d = 1;
while(b > 0) {
if (b%2 == 1) d = d*a;
b = b/2;
if (b > 0) a = a*a;
}
return d;
}
|
| |
Iteration |
a
|
b
|
d
|
---|
Start |
3 |
14 |
1 |
End 1st |
32 = 9 |
7 |
1 |
End 2nd |
(32)2 =
34 = 81 |
3 |
1 * 32 = 32 = 9 |
End 3rd |
(34)2 =
38 = 6561 |
1 |
32 * 34 =
36 = 9 * 81 = 729 |
End 4th |
38 = 6561 |
0 |
36 * 38 =
314 = 729 * 6561 = 4782969 |
End 5th |
No 5th loop |
| |
End 6th | No 6th loop |
| |
|