622FThe Sum of the k-th Powers

题目大意

求$\sum_{i=1}^{n} i^k$

分析

我们发现这是一个$k+1$次多项式

因此我们求出前$k+2$项然后插值即可

由于$x_i = i$

因此公式里面的乘机可以通过预处理然后循环中乘逆元的方式快速得到

代码

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
const int mod = 1e9+7;
int n,k,p[1000100],inv[1000100],sum[1000100],Ans;
inline int pw(int x,int tot){
    int res=1;
    while(tot){
      if(tot&1)res=1ll*res*x%mod;
      x=1ll*x*x%mod;
      tot>>=1;
    }
    return res;
}
int main(){
    int i,j,t=1;
    scanf("%d%d",&n,&k);
    p[0]=1;
    for(i=1;i<=N;i++)p[i]=1ll*p[i-1]*i%mod;
    inv[N]=pw(p[N],mod-2);
    for(i=N-1;i>=0;i--)inv[i]=1ll*inv[i+1]*(i+1)%mod;
    for(i=1;i<=k+2;i++)sum[i]=(sum[i-1]+pw(i,k))%mod;
    if(n<=k+2){printf("%d\n",sum[n]);return 0;}
    for(i=1;i<=k+2;i++)t=1ll*t*(n-i)%mod;
    for(i=1;i<=k+2;i++){
      int res=1ll*sum[i]*t%mod*pw(n-i,mod-2)%mod*inv[k+2-i]%mod*inv[i-1]%mod;
      if((k+2-i)&1)res=mod-res;
      Ans=(Ans+res)%mod;
    }
    printf("%d\n",Ans);
    return 0;
}

 

posted @ 2019-09-06 07:55  水题收割者  阅读(173)  评论(0编辑  收藏  举报