Power
Details
Write the recursive function power(int base, int exponent)
, that returns base
raised to the exponent
power.
Example
The function calls:
power(2, 2)
power(2, 3)
power(2, 10)
power(3, 3)
Would produce the output:
4
8
1024
27
More Power
Details
Write the recursive function more_power(int base, int exponent)
again. This time use the following recursive definition:
\(x^1 = x\)
\(x^y = x^{y / 2} \cdot x^{y / 2}\) (if y is even and greater than 1)
\(x^y = x \cdot x^{(y - 1) / 2} \cdot x^{(y - 1) / 2}\) (if y is odd and greater than 2)
Example
The function calls:
more_power(2, 2)
more_power(2, 3)
more_power(2, 10)
more_power(3, 3)
Would produce the output:
4
8
1024
27
Even More Power
Details
Modify both of your power functions so that they print multiply
every time they perform a multiplication. If they multiply twice on one line, they should print multiply
twice.
Count the number of times that each function multiplies when you call them with an exponent of 4
. If the more_power
function doesn’t print multiply
fewer times, fix it so that it does.
Example
The function calls:
std::cout << power(2, 10) << std::endl;
std::cout << "-----------------" << std::endl;
std::cout << more_power(2, 10) << std::endl;
Would produce the output:
multiply
multiply
multiply
multiply
multiply
multiply
multiply
multiply
multiply
1024
---------
multiply
multiply multiply
multiply
1024