Skip to content

Commit b7b5972

Browse files
committed
Day 10 Add power function
1 parent fcb7c48 commit b7b5972

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66

77
| Current Status| Stats |
88
| :------------: | :----------: |
9-
| Total Problems | 145 |
10-
| Current Streak | 9 days |
9+
| Total Problems | 146 |
10+
| Current Streak | 10 days |
1111
| Longest Streak | 91 ( August 17, 2015 - November 15, 2015 ) |
1212

1313
</center>
@@ -146,6 +146,7 @@ Include contains single header implementation of data structures and some algori
146146
| Encrypt and then decrypts a text using Caeser Cipher. | [caeser_cipher.cpp](common_ds_algo_problems/caeser_cipher.cpp)|
147147
| Encrypt and then decrypts a text using Vigenère cipher. | [vigenere_cipher.cpp](common_ds_algo_problems/vigenere_cipher.cpp)|
148148
| Generate binary numbers between 1 to N efficiently. |[n_binary.cpp](common_ds_algo_problems/n_binary.cpp)|
149+
| Implement power function | [power_function.cpp](common_ds_algo_problems/power_function.cpp)|
149150

150151
### Math Problems
151152
| Problem | Solution |
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* Implement pow(a, b) function.
3+
* We can recursively call a sub-problem
4+
* if n is even, then pow(a,b) = pow(a, b/2) * pow(a, b/2);
5+
* if n is odd then, pow(a, b) = a * pow(a, b/2) * pow(a, b/2);
6+
*/
7+
8+
#include <iostream>
9+
10+
int power(int a, int b)
11+
{
12+
// base condition
13+
//
14+
if (b == 0)
15+
{
16+
return 1;
17+
}
18+
19+
// sub-problem for this recursive call.
20+
//
21+
int p = power(a, b/2);
22+
23+
// if b is odd
24+
if (b & 1)
25+
{
26+
return (a * p * p);
27+
}
28+
else
29+
{
30+
// if b is even
31+
return (p * p);
32+
}
33+
}
34+
35+
int main()
36+
{
37+
int a, b;
38+
std::cout << "Calculating pow(a,b):\n";
39+
std::cout << "Enter a:";
40+
std::cin >> a;
41+
std::cout << "Enter b:";
42+
std::cin >> b;
43+
std::cout << "pow(a,b) :" << power(a, b) << std::endl;
44+
}
45+

0 commit comments

Comments
 (0)