Challenge: Fast Power (mod)
Completed
Read a, b and m. Print ab mod m using a recursive function that halves b each time. Take the remainder after every multiplication so numbers stay small.
Input
Three whole numbers a b m (0 ≤ a, b ≤ 1018, 1 ≤ m ≤ 109).
Output
One number.
Example
Input
2 10 1000
Output
24
Editor
C++
Hints
Base case: b == 0 gives 1 (mod m).
half = powmod(a, b / 2, m); square it, then multiply by a if b is odd.
Use % m after every multiplication.
Solution explanation
About 60 calls even for b = 10¹⁸. Because every value stays below m ≤ 10⁹, products fit in a long long.
Show solution
#include <iostream>
using namespace std;
long long powmod(long long a, long long b, long long m) {
if (b == 0) return 1 % m;
long long half = powmod(a, b / 2, m);
long long result = half * half % m;
if (b % 2 == 1) result = result * (a % m) % m;
return result;
}
int main() {
long long a, b, m;
cin >> a >> b >> m;
cout << powmod(a, b, m) << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module