forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
power_function.cpp
45 lines (39 loc) · 829 Bytes
/
power_function.cpp
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
/*
* Implement pow(a, b) function.
* We can recursively call a sub-problem
* if n is even, then pow(a,b) = pow(a, b/2) * pow(a, b/2);
* if n is odd then, pow(a, b) = a * pow(a, b/2) * pow(a, b/2);
*/
#include <iostream>
int power(int a, int b)
{
// base condition
//
if (b == 0)
{
return 1;
}
// sub-problem for this recursive call.
//
int p = power(a, b/2);
// if b is odd
if (b & 1)
{
return (a * p * p);
}
else
{
// if b is even
return (p * p);
}
}
int main()
{
int a, b;
std::cout << "Calculating pow(a,b):\n";
std::cout << "Enter a:";
std::cin >> a;
std::cout << "Enter b:";
std::cin >> b;
std::cout << "pow(a,b) :" << power(a, b) << std::endl;
}