Is there any algorithm to calculate (1^x + 2^x + 3^x + ... + n^x) mod 1000000007
?
Note: a^b
is the b-th power of a.
The constraints are 1 <= n <= 10^16, 1 <= x <= 1000
. So the value of N is very large.
I can only solve for O(m log m)
if m = 1000000007
. It is very slow because the time limit is 2 secs.
Do you have any efficient algorithm?
There was a comment that it might be duplicate of this question, but it is definitely different.
What is modulo 1000000007 in competitive programming? It is used to prevent data overflow.
1000... 7 are prime numbers and 1000000007 is the biggest one that fits in 32-bit integer. Since prime numbers are used to calculate hash (by finding the remainder of the division by prime), 1000000007 is good for calculating 32-bit hash.
Given 2 integers x and n, you have to calculate x to the power of n, modulo 10^9+7 i.e. calculate (x^n) % (10^9+7). In other words, you have to find the value when x is raised to the power of n, and then modulo is taken with 10^9+7. a%b means the remainder when a divides b.
You can sum up the series
1**X + 2**X + ... + N**X
with the help of Faulhaber's formula and you'll get a polynomial with an X + 1
power to compute for arbitrary N
.
If you don't want to compute Bernoulli Numbers, you can find the the polynomial by solving X + 2
linear equations (for N = 1, N = 2, N = 3, ..., N = X + 2
) which is a slower method but easier to implement.
Let's have an example for X = 2
. In this case we have an X + 1 = 3
order polynomial:
A*N**3 + B*N**2 + C*N + D
The linear equations are
A + B + C + D = 1 = 1
A*8 + B*4 + C*2 + D = 1 + 4 = 5
A*27 + B*9 + C*3 + D = 1 + 4 + 9 = 14
A*64 + B*16 + C*4 + D = 1 + 4 + 9 + 16 = 30
Having solved the equations we'll get
A = 1/3
B = 1/2
C = 1/6
D = 0
The final formula is
1**2 + 2**2 + ... + N**2 == N**3 / 3 + N**2 / 2 + N / 6
Now, all you have to do is to put an arbitrary large N
into the formula. So far the algorithm has O(X**2)
complexity (since it doesn't depend on N
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With