Created
October 17, 2013 13:48
-
-
Save shobhit6993/7025211 to your computer and use it in GitHub Desktop.
This is a non-recursive implementation of exponentiation in O(log(n)) with MOD. Takes up more space as compared to the recursive implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//non recursive version | |
int64_t powMod(int64_t a,int64_t power) | |
{ | |
if (a==1) | |
{ | |
return 1; | |
} | |
int64_t count=0, answer=1; | |
std::vector<int64_t> powerDP; | |
powerDP.push_back(a); | |
int64_t powerTemp=power>>1; | |
while(powerTemp!=0) | |
{ | |
int64_t temp=powerDP.back()*powerDP.back(); | |
temp=(temp>=MOD)?temp%MOD:temp; | |
powerDP.push_back(temp); | |
powerTemp=powerTemp>>1; | |
} | |
while(power!=0) | |
{ | |
if (power & 1) | |
{ | |
answer=answer* powerDP[count]; | |
answer=(answer>=MOD)?answer%MOD:answer; | |
} | |
power=power>>1; | |
count++; | |
} | |
return answer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment