Lesson 23 of 50 intermediate

Powers and Modular Arithmetic

Handle astronomically huge numbers like a pro

Open interactive version (quiz + challenge)

Real-world analogy

Modulo is like a clock — after 12, it goes back to 1. No matter how many hours pass, the clock only shows 1 to 12. Modulo works the same way: no matter how big a number gets, modulo wraps it back into a manageable range.

What is it?

Powers and modular arithmetic are fundamental tools in competitive programming. A power (a^b) means multiplying a number by itself multiple times, and modulo (%) keeps huge numbers within a manageable range by taking the remainder after division. Together, they let you handle calculations that would otherwise cause integer overflow.

Real-world relevance

Modular arithmetic is everywhere! Clocks use mod 12 (or mod 24). Days of the week use mod 7. Cryptography (like the RSA algorithm that secures the internet) relies heavily on modular exponentiation. Even check digits on credit cards use modular arithmetic to detect typos.

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // Computing a^b with modulo
    long long a = 2, b = 10;
    long long mod = 1000000007;
    long long result = 1;
    for (int i = 0; i < b; i++) {
        result = (result * a) % mod;
    }
    cout << a << "^" << b << " mod " << mod << " = " << result << "\n";

    // Fibonacci with modulo
    int n = 20;
    long long fib[21];
    fib[0] = 0;
    fib[1] = 1;
    for (int i = 2; i <= n; i++) {
        fib[i] = (fib[i-1] + fib[i-2]) % mod;
    }
    cout << "fib(" << n << ") = " << fib[n] << "\n";

    // Simple modular arithmetic demo
    long long x = 1000000006, y = 1000000005;
    long long safeSum = ((x % mod) + (y % mod)) % mod;
    cout << "Safe sum mod = " << safeSum << "\n";

    return 0;
}

Line-by-line walkthrough

  1. 1. long long a = 2, b = 10; — we set up our base (a=2) and exponent (b=10). We use long long because even intermediate results can be large.
  2. 2. long long mod = 1000000007; — this is the standard CP modulo value. It is a prime number just over one billion.
  3. 3. long long result = 1; — we start with 1 because anything raised to the power 0 is 1. We will multiply this by a, b times.
  4. 4. for (int i = 0; i < b; i++) { result = (result * a) % mod; } — each iteration multiplies result by a and takes modulo. After 10 iterations, result = 2^10 % mod = 1024.
  5. 5. fib[0] = 0; fib[1] = 1; — the Fibonacci sequence starts with 0 and 1. These are our base cases.
  6. 6. fib[i] = (fib[i-1] + fib[i-2]) % mod; — each Fibonacci number is the sum of the previous two, and we take modulo to prevent overflow.
  7. 7. long long safeSum = ((x % mod) + (y % mod)) % mod; — this demonstrates the modular addition rule. Even though x and y are huge, the result fits in a long long.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int a = 2, b = 40;
    int mod = 1000000007;
    int result = 1;
    for (int i = 0; i < b; i++) {
        result = (result * a) % mod;
    }
    cout << result << "\n";
    return 0;
}
Need a hint?
Look at the data types. When result is close to 1000000007 and you multiply it by 2, how big can that intermediate value get? Can an int hold it?
Show answer
The bug is using int instead of long long for result. When result is near 1000000007 (about 10^9), multiplying by a (which is 2) gives about 2*10^9, which overflows a 32-bit int (max ~2.1*10^9). The fix is to change 'int result = 1;' to 'long long result = 1;' and also make a and mod long long to be safe.

Explain like I'm 5

Imagine you are counting laps around a small track. The track is only 10 meters around. If you run 37 meters, you have done 3 full laps and are 7 meters into your 4th lap. That 7 is 37 % 10! Modulo tells you where you are on the track, no matter how far you have run. In programming, when numbers get SUPER huge (like trillions), modulo keeps them on a small track so your computer does not explode!

Fun fact

The Fibonacci sequence appears in nature everywhere — the number of petals on most flowers is a Fibonacci number (3, 5, 8, 13, 21...), sunflower seed spirals follow Fibonacci patterns, and even the proportions of the human body approximate the golden ratio, which is closely related to Fibonacci numbers!

Hands-on challenge

Write a program that reads two numbers a and b, then computes a^b modulo 1000000007 using a loop. Then also compute the first 30 Fibonacci numbers modulo 1000000007 and print them all. Test with a=2, b=30 (answer should be 1073741824 % 1e9+7 = 73741817).

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero