Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use the integer constant 1_000_000_007, reduce values before they can overflow, normalize negative results, and implement division with a modular inverse. The notation 10^9 + 7 means the prime integer 1,000,000,007—not a floating-point power expression.

This guide explains the arithmetic, overflow rules, inverses, exponentiation, combinations, huge inputs, and safe implementations in C++, Java, Python, JavaScript, and C#.

The constant and the invariant

Define:

MOD = 1_000_000_007

A normalized modular value is always in 0 <= x < MOD. Values that differ by a multiple of MOD are equivalent, so for integers:

(a + b) % MOD == ((a % MOD) + (b % MOD)) % MOD
(a - b) % MOD == ((a % MOD) - (b % MOD)) % MOD
(a * b) % MOD == ((a % MOD) * (b % MOD)) % MOD

Reducing after each operation is valid, but only if the intermediate expression itself fits its type. The largest product of two normalized residues is 1,000,000,006² = 1,000,000,012,000,000,036, below 2^63 - 1. Thus signed 64-bit multiplication is safe when both operands have already been reduced.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why this prime appears so often

1,000,000,007 is large enough for most contest answers, is odd, and is prime. Primality means every nonzero residue has a modular inverse, enabling division and the exponentiation formula a^(MOD-2) mod MOD. These properties apply to this modulus; do not assume an arbitrary problem modulus is prime.

Addition, subtraction, multiplication, and normalization

Addition

If a and b are normalized, their sum is below 2*MOD:

long long add_mod(long long a, long long b) {
    a += b;
    if (a >= MOD) a -= MOD;
    return a;
}

Use this branch only when both inputs are already in the normalized range. Otherwise normalize first or use (a + b) % MOD with a sufficiently wide type.

Subtraction and negative remainders

Mathematically, 3 - 5 mod MOD is MOD - 2. In C++, Java, JavaScript, and C#, the remainder of a negative dividend can itself be negative. A general helper is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
long long normalize(long long x) {
    x %= MOD;
    if (x < 0) x += MOD;
    return x;
}

When both operands are normalized, this is safe:

long long sub_mod(long long a, long long b) {
    a -= b;
    if (a < 0) a += MOD;
    return a;
}

The compact form (a - b + MOD) % MOD also assumes a and b are each in [0, MOD). One added modulus is not enough for an arbitrary negative value.

Python differs: with a positive modulus, (-2) % MOD is already nonnegative.

Multiplication and overflow

The remainder operation happens after multiplication. Therefore this can overflow before % MOD runs:

int result = (a * b) % MOD; // wrong when a and b are large

Widen first:

long long result = (1LL * a * b) % MOD;

In C++, signed overflow is undefined behavior; unsigned wraparound is modulo a power of two, not modulo 1,000,000,007. See the C++ arithmetic rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Overflow rules by language

Language Main hazard Safe default
C++ Signed overflow is undefined; narrow operands multiply narrowly. Cast to long long before multiplication.
Java int multiplication can wrap before assignment to long; long also wraps on overflow. Use ((long)a * b) % MOD.
Python Integers grow automatically, but huge unreduced values cost time and memory. Reduce regularly.
JavaScript Number is exact only through 2^53 - 1, far below MOD². Use BigInt consistently.
C# Overflow behavior changes in checked and unchecked contexts. Use long and understand the active context.

Java’s remainder semantics are specified in the Java Language Specification. JavaScript remainder and BigInt rules are documented by MDN. C# checked arithmetic and remainder behavior are described in Microsoft’s documentation.

Binary modular exponentiation

Never build a huge power and then take its remainder. Binary exponentiation takes O(log e) multiplications:

long long mod_pow(long long base, long long exponent) {
    base = normalize(base);
    long long result = 1;
    while (exponent > 0) {
        if (exponent & 1) result = result * base % MOD;
        base = base * base % MOD;
        exponent >>= 1;
    }
    return result;
}

Because base and result remain below MOD, the products fit signed 64-bit C++ or Java long.

Modular division and inverses

Ordinary division is not modular division. The expression (a / b) % MOD divides first and loses information. Instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
a / b mod MOD = a * inverse(b) mod MOD

An inverse exists only when gcd(b, MOD) = 1. Since this modulus is prime, every nonzero b % MOD has an inverse:

long long mod_inverse(long long b) {
    return mod_pow(b, MOD - 2);
}

long long quotient = a % MOD * mod_inverse(b) % MOD;

Fermat’s exponent MOD - 2 is not a universal inverse algorithm: it depends on a prime modulus and a nonzero denominator. For a composite modulus, use the extended Euclidean algorithm when the gcd is one. Reject zero modulo the modulus.

Factorials and combinations

For 0 <= k <= n and parameters below the modulus, precompute:

fact[i] = fact[i - 1] * i % MOD;
inv_fact[n] = mod_pow(fact[n], MOD - 2);
for (int i = n; i > 0; --i)
    inv_fact[i - 1] = inv_fact[i] * i % MOD;

C(n, k) = fact[n] * inv_fact[k] % MOD * inv_fact[n-k] % MOD;

If n >= MOD, a factorial can be zero modulo MOD; this simple inverse-factorial method no longer automatically applies. Large-parameter problems may require Lucas’s theorem or another number-theoretic technique.

Reducing a huge decimal input

When an input integer does not fit a native type, process its digits:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
long long remainder_of_decimal(const string& s) {
    long long r = 0;
    for (char c : s)
        r = (r * 10 + (c - '0')) % MOD;
    return r;
}

Handle a leading minus sign separately and normalize the final result. This works because each new prefix is old_prefix * 10 + digit.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Complete language templates

C++

constexpr long long MOD = 1'000'000'007LL;

long long normalize(long long x) {
    x %= MOD;
    if (x < 0) x += MOD;
    return x;
}
long long mod_pow(long long a, long long e) {
    a = normalize(a);
    long long r = 1;
    while (e) {
        if (e & 1) r = r * a % MOD;
        a = a * a % MOD;
        e >>= 1;
    }
    return r;
}

Java

static final long MOD = 1_000_000_007L;
static long normalize(long x) {
    x %= MOD;
    return x < 0 ? x + MOD : x;
}
static long modPow(long base, long exp) {
    base = normalize(base);
    long result = 1L;
    while (exp > 0) {
        if ((exp & 1L) != 0) result = result * base % MOD;
        base = base * base % MOD;
        exp >>= 1;
    }
    return result;
}

Do not write long result = (a * b) % MOD when a and b are int; cast one operand first.

Python

MOD = 1_000_000_007

def mod_pow(base, exponent):
    return pow(base, exponent, MOD)

def mod_inverse(x):
    return pow(x, MOD - 2, MOD)

Python’s three-argument pow performs modular exponentiation directly.

JavaScript

const MOD = 1000000007n;
function normalize(x) {
    x %= MOD;
    return x < 0n ? x + MOD : x;
}
function modPow(base, exponent) {
    base = normalize(base);
    let result = 1n;
    while (exponent > 0n) {
        if (exponent & 1n) result = result * base % MOD;
        base = base * base % MOD;
        exponent >>= 1n;
    }
    return result;
}

Call modPow(2n, 100n), not modPow(2, 100). Mixing Number and BigInt, such as 1n + 1, throws a TypeError.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

C#

const long MOD = 1_000_000_007L;
static long Normalize(long x) {
    x %= MOD;
    if (x < 0) x += MOD;
    return x;
}
static long ModPow(long value, long exponent) {
    value = Normalize(value);
    long result = 1;
    while (exponent > 0) {
        if ((exponent & 1) != 0) result = result * value % MOD;
        value = value * value % MOD;
        exponent >>= 1;
    }
    return result;
}

Debugging checklist

  • Is the constant an integer literal, not pow(10, 9) + 7 or 1e9 + 7?
  • Did multiplication occur in a wide enough type before %?
  • Can subtraction produce a negative remainder?
  • Are JavaScript operands all BigInt?
  • Did you replace division with an inverse?
  • Is the denominator nonzero and coprime to the modulus?
  • Are values reduced before the next potentially overflowing operation?
  • Is the returned answer normalized to [0, MOD)?

A small example

With modulus 13, 3 - 5 = -2, which is congruent to 11. Code using signed remainders must normalize -2 to 11. Division works only through an inverse: the inverse of 5 modulo 13 is 8 because 5 * 8 = 40 ≡ 1; therefore 3 / 5 ≡ 3 * 8 ≡ 11 (mod 13). The same rules apply with MOD = 1,000,000,007, provided the stated type and prime-modulus assumptions hold.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.