# Codeforces D. The Sum of the k-th Powers（拉格朗日插值）

## 题目描述：

The Sum of the k-th Powers

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

There are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.

Find the value of the sum modulo 109 + 7 (so you should find the remainder after dividing the answer by the value 109 + 7).

Input

The only line contains two integers n, k (1 ≤ n ≤ 109, 0 ≤ k ≤ 106).

Output

Print the only integer a — the remainder after dividing the value of the sum by the value 109 + 7.

Examples

Input

Copy

4 1


Output

Copy

10


Input

Copy

4 2


Output

Copy

30


Input

Copy

4 3


Output

Copy

100


Input

Copy

4 0


Output

Copy

4


## 思路：

### 拉格朗日插值公式

$$f(x)=\sum_{i=0}^n y_i\prod_{j!=i}\frac{x-x_j}{x_i-x_j}$$.

$P_i=\prod_{j=0}^i(x-x_j)$$S_i=\prod_{j=i}^n(x-x_j)$.

## 代码：

#include <iostream>
#define max_n 1000006
const long long mod = 1000000007;
using namespace std;
int k;
int n;
long long fac[max_n];
long long y[max_n];
long long pi = 1;
long long q_mod(long long a,long long b,long long mod)
{
long long res = 1;
while(b)
{
if(b&1)
{
res = (res*a)%mod;
}
a = (a*a)%mod;
b>>=1;
}
return res;
}

int main()
{
cin >> n >> k;
y[0] = 0;
for(int i = 1;i<=k+2;i++)
{
y[i] = (y[i-1]+q_mod(i,k,mod))%mod;
}
if(n<=k+2)
{
cout << y[n] << endl;
return 0;
}
fac[0] = 1;
for(int i = 1;i<=max_n;i++)
{
fac[i] = (fac[i-1]*i)%mod;
}
for(int i = 1;i<=k+2;i++)
{
pi = (pi*(n-i))%mod;
}
long long ans = 0;
for(int i = 1;i<=k+2;i++)
{
long long f = ((k+2-i)%2)?-1:1;
long long inv = q_mod(fac[k+2-i]%mod*fac[i-1]%mod,mod-2,mod);
long long inv2 = q_mod(n-i,mod-2,mod);
ans = (ans+f*y[i]*pi%mod*inv%mod*inv2%mod)%mod;

}
cout << (ans+mod)%mod << endl;
return 0;
}


## 参考文章：

Wolfycz，自然数幂和，https://www.cnblogs.com/Wolfycz/p/10622577.html，浅谈算法——拉格朗日插值，https://www.cnblogs.com/Wolfycz/p/10624678.html

qscqesze，Educational Codeforces Round 7 F. The Sum of the k-th Powers 拉格朗日插值法，https://www.cnblogs.com/qscqesze/p/5207132.html

sdfzchy，【CF622F】The Sum of the k-th Powers （拉格朗日插值法），https://blog.csdn.net/sdfzchy/article/details/78307534

posted @ 2019-08-13 21:23  小张人  阅读(...)  评论(...编辑  收藏