-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindPower.c
80 lines (61 loc) · 1.58 KB
/
FindPower.c
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
Calculate x raised to the power of given n
eg:
2.0 ^ 5 = 32.000000
7.0 ^ 11 = 1977326743.000000
For explanation, refer to the following link
https://leetcode.com/problems/powx-n/discuss/1337794/JAVA-C%2B%2B-%3A-Simple-or-O-log(n)-or-Easy-or-Faster-than-100-or-Explained
*/
#include<stdio.h>
double getPowViaIteration(double, int);
double getPowViaRecursion(double, int);
double getPowViaTailRecursion(double, int, double);
int main() {
double x = 2.0;
int n = 5;
printf("%lf\n", getPowViaIteration(x, n));
printf("%lf\n", getPowViaRecursion(x, n));
printf("%lf\n", getPowViaTailRecursion(x, n, 1));
return 0;
}
/*
Time: O(logn)
Space: O(1)
*/
double getPowViaIteration(double x, int n) {
double pow = 1;
while(n != 0) {
if((n & 1) == 1) { // if((n & 1) == 1) is equivalent to if((n % 2) == 1)
pow *= x;
}
x *= x;
n >>= 1; // n >>= 1 is equivalent to n /= 2
}
return pow;
}
/*
Time: O(logn)
Space: O(logn)
*/
double getPowViaRecursion(double x, int n) {
if(n == 0) {
return 1;
}
if((n & 1) == 1) { // if((n & 1) == 1) is equivalent to if((n % 2) == 1)
return x * getPowViaRecursion(x * x, n >> 1); // n >> 1 is equivalent to n / 2
}
return getPowViaRecursion(x * x, n >> 1);
}
/*
Time: O(logn)
Space: O(1)
*/
double getPowViaTailRecursion(double x, int n, double pow) {
if(n == 0) {
return pow;
}
if((n & 1) == 1) { // if((n & 1) == 1) is equivalent to if((n % 2) == 1)
return getPowViaTailRecursion(x * x, n >> 1, pow * x); // n >> 1 is equivalent to n / 2
}
return getPowViaTailRecursion(x * x, n >> 1, pow);
}