-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path11_fast_exponentiation_using_bitmasking.cpp
80 lines (60 loc) · 1.58 KB
/
11_fast_exponentiation_using_bitmasking.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
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
/*
Topic: Fast Exponentiation using Bitmasking
- Exponentiation/Power using Bitmasking
Eg: Input : n=2
p=6
Output: 64
*/
#include <iostream>
using namespace std;
// Exponentiation/Power using Bitmasking
int power_optimised(int num, int power)
{
int ans = 1;
while(power)
{
int last_bit = power&1;
if(last_bit == 1)
{
ans = ans*num;
}
num = num*num; // Square up
power = power>>1; // Discard the last bit
}
return ans;
/*
Approach:
- Iterate over each binary value of 'power' & perform the below operations:
1. Multiply 'n' by its current value
2. if extracted_bit = 1 => multiply result-value by n (i.e current value of n)
extracted_bit = 0 => skip
Eg: when n = 3
p = 5 (101)
Current value of n (for each binary value of p) : n=81 n=9 n=3
1 0 1
Output = 81 * (skip) * 3
= 243
*/
}
// function to drive code
int main()
{
int num, power;
cout << "Enter [Number & Power]: ";
cin >> num >> power;
cout << "Output: " << power_optimised(num, power);
cout << endl;
return 0;
}
/*
OUTPUT:
Case 1:
Enter [Number & Power]: 5 2
Output: 25
Case 2:
Enter [Number & Power]: 2 10
Output: 1024
Case 3:
Enter [Number & Power]: 3 5
Output: 243
*/