-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_power_calculator.cpp
More file actions
53 lines (47 loc) · 961 Bytes
/
recursive_power_calculator.cpp
File metadata and controls
53 lines (47 loc) · 961 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
using namespace std;
bool isEven(int n)
{
return n % 2 == 0;
}
bool isOdd(int n)
{
return !isEven(n);
}
double power(int x, int n)
{
// base case
if (n == 0)
{
return 1;
}
// case: n is negative
if (n < 0)
{
return 1 / (power(x, (-n)));
}
// case: n is odd
if (isOdd(n))
{
return x * power(x, n - 1);
}
// case: n is even
int squareRoot = power(x, n / 2);
return squareRoot * squareRoot;
}
void displayPower(int x, int n, double expectedResult)
{
double result = power(x, n);
cout << x << " to the " << n << " is " << result << " (" << (result == expectedResult ? "TRUE" : "FALSE") << ")" << endl
<< endl;
}
int main()
{
displayPower(3, 0, 1);
displayPower(3, 1, 3);
displayPower(3, 2, 9);
displayPower(3, -1, (1.0 / 3.0));
displayPower(5, 3, 125);
displayPower(4, -4, (1.0 / 256.0));
return 0;
}