Technique · CP 2400+
Lagrange Interpolation
If the answer f(n) is a polynomial of degree d in n (sum of i^k has degree k+1), compute f(0..d) directly. Then evaluate f at a huge n with Lagrange's formula in O(d), using prefix and suffix products.
0%
mastery
0/2 solved
0/2 solved
Recognise it
The signal
n up to 1e9-1e18, but the answer is a low-degree polynomial in n
1Brute force
Sum directly up to n: O(n).
2The observation
n is too large to iterate.
3Why it works
A degree-d polynomial is determined by any d+1 points.
Reach for it when
- +sum of i^k with k <= 1e6
- +a DP whose values are polynomials in a large parameter
Not when
- ×the answer is not polynomial in n (exponential terms call for matexp)
Practice
0/2 solved
- Stranger TreesCodeforces2600
- The Sum of the k-th PowersCodeforces2600
Pitfalls
Misconceptions
- !using d points instead of d+1
- !O(d2) evaluation when consecutive integer points allow O(d)
Go deeper1 combinations · resources
Combinations
Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem+Lagrange Interpolation
count spanning trees sharing exactly k edges with a given tree, n <= 100
- Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem:
- matrix-tree determinants for spanning trees with weighted edges
- Lagrange Interpolation:
- recover the polynomial in x from n evaluations