Skip to content

Commit f15c7a9

Browse files
committed
Day-46 Implementation of pow(x,y)
1 parent 6d02b49 commit f15c7a9

File tree

2 files changed

+42
-3
lines changed

2 files changed

+42
-3
lines changed

README.md

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
| Current Status| Stats |
66
| :------------: | :----------: |
7-
| Total Problems | 64 |
8-
| Current Streak | 45 |
9-
| Longest Streak | 45 ( August 17, 2015 - September 30, 2015 ) |
7+
| Total Problems | 65 |
8+
| Current Streak | 46 |
9+
| Longest Streak | 46 ( August 17, 2015 - October 1, 2015 ) |
1010

1111
</center>
1212

@@ -105,6 +105,7 @@ Include contains single header implementation of data structures and some algori
105105
| :------------ | :----------: |
106106
| Print all the permutations of a string. Example: Permutations of ABC are ABC, ACB, BCA, BAC, CAB, CBA | [string_permutations.cpp] (math_problems/string_permutations.cpp) |
107107
| Euclidean algorithm to find greatest common divisor of two numbers. (Iterative and recursive)|[gcd.cpp](math_problems/gcd.cpp)|
108+
| Implement pow(x,y) using divide and conquer approach. Try implementing it in O(logn)| [pow.cpp](math_problems/pow.cpp)|
108109

109110
### Stack Problems
110111
| Problem | Solution |

math_problems/pow.cpp

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* A simple divide and conquer approach to calculate pow(x,y)
3+
*/
4+
5+
#include <iostream>
6+
7+
8+
double pow( double x, int y )
9+
{
10+
//base case
11+
if ( y == 0 ) {
12+
return 1;
13+
}
14+
double temp = pow(x, y/2);
15+
if ( y % 2 == 0 ) {
16+
return temp * temp;
17+
} else {
18+
if ( y > 0 ) {
19+
return x * temp * temp;
20+
} else {
21+
return ( temp * temp ) / x;
22+
}
23+
}
24+
}
25+
26+
int main()
27+
{
28+
std::cout << "Program to calculate power y to the base x\n";
29+
double x;
30+
int y;
31+
std::cout << "Enter base : ";
32+
std::cin >> x;
33+
std::cout << "Enter power(int + or -) : ";
34+
std::cin >> y;
35+
std::cout << "Power " << y << " to the base " << x << " is: ";
36+
std::cout << pow(x, y) << std::endl;
37+
return 0;
38+
}

0 commit comments

Comments
 (0)