How can I calculate (a ^ b) % c
, where 0 <= a, b, c <= 10^18
.
Here, (a ^ b)
means a
to the power b
, not a xor b
.
My current code for the problem is:
unsigned long long bigMod(unsigned long long b,
unsigned long long p,
unsigned long long m){
if(b == 1) return b;
if(p == 0) return 1;
if(p == 1) return b;
if(p % 2 == 0){
unsigned long long temp = bigMod(b, p / 2ll, m);
return ((temp) * (temp) )% m;
}else return (b * bigMod(b, p-1, m)) % m;
}
For this input:
a = 12345 b = 123456789 and c = 123456789012345
the expected output should be:
59212459031520
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…