KatInterview

Modular Exponentiation of a Polynomial at a Point

Math & Bit ManipulationAuto-graded · 17 test cases
MediumAuto-gradedMath & Bit Manipulationmathmodular arithmeticnumber theory

Last updated

Tests the ability to evaluate a polynomial modulo a prime, raise the result to a large power modulo the same prime, and apply Fermat's little theorem for efficiency.

Modular Exponentiation of a Polynomial at a Point

You are given:

  • A list of integer coefficients coeffs representing a polynomial P where coeffs[i] is the coefficient of x^i (index 0 is the constant term).
  • An integer x — the point at which to evaluate the polynomial.
  • A non-negative integer exp — the exponent to raise the evaluated result to.
  • A prime integer p — the modulus.

Your task is to compute:

(P(x))^exp mod p

where P(x) = coeffs[0] + coeffs[1]·x + coeffs[2]·x² + … + coeffs[n-1]·x^(n-1).

To keep intermediate values manageable, reduce every intermediate computation modulo p.

Key requirement: large exponents

The exponent exp can be astronomically large (up to 10^18). You must use Fermat's Little Theorem to reduce the effective exponent before performing fast modular exponentiation:

Since p is prime and the base may be non-zero mod p, use the fact that a^(p−1) ≡ 1 (mod p) for a not divisible by p.

Specifically:

  • If P(x) mod p == 0, the answer is 0 (for any exp > 0), or 1 if exp == 0.
  • Otherwise, reduce exp modulo (p − 1) before computing the power, then apply fast modular exponentiation.

Constraints

  • 1 ≤ len(coeffs) ≤ 500
  • Each coefficient satisfies -10^9 ≤ coeffs[i] ≤ 10^9
  • -10^9 ≤ x ≤ 10^9
  • 0 ≤ exp ≤ 10^18
  • p is a prime, 3 ≤ p ≤ 10^9 + 7
  • The answer is always a single integer in [0, p − 1]

Examples

Example 1

Input: poly_power_mod([1, 2, 1], 3, 4, 7)

Output: 2

Example 2

Input: poly_power_mod([0, 1], 5, 1000000000000000000, 1000000007)

Output: 921116510

Example 3

Input: poly_power_mod([3], 0, 0, 13)

Output: 1

Hints

Hint 1

First evaluate P(x) mod p using Horner's method or direct summation, reducing mod p at each step to avoid overflow.

Hint 2

Apply Fermat's Little Theorem: if the base b = P(x) mod p is non-zero, then b^exp mod p == b^(exp mod (p-1)) mod p — this shrinks the exponent before calling pow().

Hint 3

Handle the two special cases separately: exp == 0 always gives 1, and base == 0 with exp > 0 always gives 0.