forked from namishkhanna/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Exponentiation.cpp
57 lines (53 loc) · 1.15 KB
/
Binary_Exponentiation.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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long int
#define inf INT_MAX
#define SINF 1e18
#define pb push_back
#define mp make_pair
#define mod 1000000007
#define PI 3.1415926535897932384626433832795
// Customized Binary Exponentiation of a^n, better than inbuilt "pow" method
// Returns More accurate Integer answers
// Time Complexity O(log(n))
ll BinaryExponentiation(ll a,ll n){
ll res=1;
while(n>0){
if(n%2!=0){
res*=a;n-=1;
}
else{
a*=a;n/=2;
}
}
return res;
}
// Modidfed Binary Exponentiation to calcualte mod answers
ll BinaryExponentiationUsingMod(ll a,ll n){
ll res=1;
while(n>0){
if(n%2!=0){
res*=a;
res=res%mod;
n-=1;
}
else{
a*=a;
a=a%mod;
n/=2;
}
}
return res;
}
int main(){
//////////////
#ifndef ONLINE_JUDGE
freopen("inputf.in","r",stdin);
freopen("outputf.in","w",stdout);
#endif
/////////////
ll a=5,n=23;
cout<<a<<" ^ "<<n<<" is: "<<BinaryExponentiation(a,n);
return 0;
}