Modular arithmetic
Exponentiation
Algorithms
Number theory
Cryptography

Calculating powa,b mod n

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Computing a^b mod n efficiently is essential in cryptography, primality testing, and competitive programming. Direct exponentiation becomes infeasible for large exponents, so modular exponentiation techniques are used. The standard solution is exponentiation by squaring, which runs in logarithmic time with respect to the exponent.

Why Naive Power Is Too Slow

A naive loop multiplying a exactly b times has linear complexity in b, and intermediate values can explode in size.

Instead, reduce modulo n during each multiplication so numbers stay bounded.

Fast Modular Exponentiation Algorithm

Exponentiation by squaring repeatedly halves the exponent.

python
1def mod_pow(a: int, b: int, n: int) -> int:
2    if n == 1:
3        return 0
4
5    a %= n
6    result = 1
7
8    while b > 0:
9        if b & 1:
10            result = (result * a) % n
11        a = (a * a) % n
12        b >>= 1
13
14    return result
15
16print(mod_pow(7, 13, 11))

Time complexity is O(log b), which is dramatically faster for large exponents.

Equivalent C Implementation

The same method in C is compact and efficient.

c
1#include <stdio.h>
2
3long long mod_pow(long long a, long long b, long long n) {
4    if (n == 1) return 0;
5    long long result = 1 % n;
6    a %= n;
7
8    while (b > 0) {
9        if (b & 1) {
10            result = (result * a) % n;
11        }
12        a = (a * a) % n;
13        b >>= 1;
14    }
15
16    return result;
17}
18
19int main(void) {
20    printf("%lld\n", mod_pow(7, 13, 11));
21    return 0;
22}

For very large values near 64-bit limits, use wider arithmetic strategies to avoid overflow before modulo reduction.

Use Built-In Support When Available

Some languages already include optimized modular exponentiation:

python
print(pow(7, 13, 11))

Python pow(base, exp, mod) is optimized in C and should be preferred unless you are implementing the algorithm for learning or portability reasons.

Cryptography Context

In RSA and Diffie-Hellman style operations, modular exponentiation is used with very large integers. Efficient implementations are core to practical security operations.

When handling cryptographic workloads, use vetted libraries instead of custom code in production security-critical systems.

Edge Cases to Handle

Validate assumptions:

  • n equal to one should return zero.
  • b equal to zero should return one modulo n.
  • Negative exponent handling depends on whether modular inverse logic is required.

Define these rules explicitly in your API contract.

Handle Large Integer Multiplication Safely

In fixed-width environments, intermediate multiplication can overflow before modulo reduction. Use wider types or multiplication helpers.

c
1unsigned long long mul_mod(unsigned long long a, unsigned long long b, unsigned long long m) {
2    __uint128_t x = (__uint128_t)a * (__uint128_t)b;
3    return (unsigned long long)(x % m);
4}
5
6unsigned long long mod_pow_safe(unsigned long long a, unsigned long long b, unsigned long long n) {
7    unsigned long long result = 1 % n;
8    a %= n;
9    while (b > 0) {
10        if (b & 1) result = mul_mod(result, a, n);
11        a = mul_mod(a, a, n);
12        b >>= 1;
13    }
14    return result;
15}

This approach avoids overflow while preserving logarithmic exponentiation complexity.

Verification Strategy

Test against known values and random checks against trusted built-ins where available. Consistency testing is critical before using custom implementations in security-sensitive modules.

Common Pitfalls

A common pitfall is computing a^b first and applying modulo later, which is both slow and often impossible for large inputs.

Another issue is integer overflow in fixed-width languages before modulo is applied.

Developers also forget to normalize a by n early, missing simple performance gains.

A final mistake is using custom implementations in cryptographic code without side-channel and correctness review.

Summary

  • Use exponentiation by squaring for fast modular power computation.
  • Keep intermediate values reduced modulo n.
  • Prefer built-in modular power helpers when available.
  • Handle edge cases explicitly and document expected behavior.
  • Use trusted libraries for security-critical cryptographic workloads.

Course illustration
Course illustration

All Rights Reserved.