Calculate Power of a Number
Given a double number, x, and an integer, n, write a function to calculate x raised to the power n.
We'll cover the following...
Statement
Given a double number, , and an integer, , implement a function to calculate raised to the power .
Example:
Given input | Power |
power(0, 0) | 1.000 |
power(2, 5) | 32.000 |
power(3, 4) | 81.000 |
power(1.5, 3) | 3.375 |
power(2, -2) | 0.250 |
Sample input
pow(2,5)
Expected output
32
Try it yourself
#include <iostream>#include <cmath>#include <vector>using namespace std;double Power(double x, int n) {//TODO: Write - Your - Codereturn x;}
Solution
A simple algorithm for this problem is to multiply x
with itself by n
times:
We can reduce the number of multiplications, in a classic divide and conquer approach, exploiting this property of exponents: