1470. Power Sum at Scale
A statistician needs the total of the first n positive integers raised to the same power k, that is 1^k + 2^k + ... + n^k, but n can be as large as 10^15 so no loop over the terms is possible. Return that total modulo 1000000007, where 0^0 is not part of the sum and for k equal to 0 every term equals 1. Here is a useful fact: the total is a polynomial in n of degree k + 1, so computing it at the points 0 to k + 1 and interpolating at n reduced modulo the prime gives the answer in O(k log p) time and O(k) space, where p is 1000000007.
Example 1
- Input:
- n = 4, k = 2
- Output:
- 30
- Explanation:
1 + 4 + 9 + 16 = 30.
Example 2
- Input:
- n = 5, k = 0
- Output:
- 5
- Explanation:
With k = 0 every term is 1, so the sum is 5.
Example 3
- Input:
- n = 10, k = 3
- Output:
- 3025
- Explanation:
The cubes of 1 to 10 add up to 3025.
Constraints
1 ≤ n ≤ 1015
0 ≤ k ≤ 1000
The result is taken modulo 109 + 7; products of residues exceed 253, so use BigInt or split multiplication in JavaScript.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(k log p)
- Space
- O(k)