Exponentiation by squaring


Exponentiating by squaring is an algorithm. It is used for quickly working out large integer powers of a number. It is also known as the square-and-multiply algorithm or binary exponentiation. It uses the binary expansion of the exponent. It is of quite general use, for example in modular arithmetic.

The algorithm is believed to have first been documented in the Sanskrit book Chandah-sûtra, about 200 BC.

Squaring algorithm


The following recursive algorithm computes xn for a positive integer n where n > 0:


This algorithm is much faster than the ordinary method to compute such a value. Multiplying x by itself, n operations are needed to calculate x n. With the method shown above, only log2(n) operations are needed.

The following algorithm computes modular exponentiation xn mod m where x is the base, n is the exponent and m is the modulus.

#include <stdio.h>
#include <stdlib.h>

unsigned long long exponentiation_by_squaring(int base, int exponent, int modulus)
    unsigned long long result = 1;
    while (exponent > 0)
        if (exponent % 2 == 1)
            result = (result * base) % modulus;
        base = (base * base) % modulus;
        exponent = exponent / 2;
    return result;

int main()
    int x, n, m;
    scanf("%d %d %d", &x, &n, &m);
    // x : base
    // n : exponent
    // m : modulus
    unsigned long long result = exponentiation_by_squaring(x, n, m);
    printf("%llu", result);

    return 0;