Exercise 15 from Chapter 2 of the textbook (p.102)
(to do with computing and understanding exponential functions)
double power1 ( double x, int n )
{
double result = 1;
for ( int i=1; i<=n; i++ )
result *= x;
return result;
}
double power2 ( double x, int n )
{
if (n == 0)
return 1;
else
return x * power2 (x, n-1);
}
double power3 ( double x, int n )
{
if (n == 0)
return 1;
else
{
double half = power3 (x, n/2);
if (n % 2)
return x * half * half;
else
return half * half;
}
}
| 3^32 | 3^19 | |
|---|---|---|
| Power1 | 32 | 19 |
| Power2 | 32 | 19 |
| Power3 | 7 | 8 |
| 3^32 | 3^19 | |
|---|---|---|
| Power2 | 32 | 19 |
| Power3 | 6 | 5 |