A^B mod C#1121

A^B mod C (Editorial)

Problem

Given integers , , and , compute: [ a^b c ] for multiple test cases. Constraints: 1 \le a, b, c < 2^{63}.

—

General Idea:

Directly computing a^b is impossible for large due to overflow. Instead, we use **modular exponentiation** (also called fast exponentiation) which calculates: [ (a^b) c ] efficiently in \mathcal{O}(\log b) time.

—

Algorithm:

  1. Initialize result = 1.

  2. While b > 0:

    • If is odd, multiply by modulo .

    • Square modulo .

    • Divide by (right shift).

  3. Return .

This approach avoids overflow by taking modulo at every multiplication. For very large numbers, we can use '__int128_t' in C++ to handle intermediate multiplication safely.

—

Time Complexity: \mathcal{O}(\log b) per test case. Memory Complexity: .

—

#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
using i128 = __int128_t;

int64 modPow(int64 a, int64 b, int64 mod) {
    a %= mod;
    int64 result = 1 % mod;

    while (b > 0) {
        if (b & 1)
            result = (i128)result * a % mod;
        a = (i128)a * a % mod;
        b >>= 1;
    }
    return result;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int64 a, b, c;
    while (cin >> a >> b >> c) {
        cout << modPow(a, b, c) << "\n";
    }
    return 0;
}