【拉格朗日求自然数幂和】cf622F

F. The Sum of the k-th Powers


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
4 1
output
10
input
4 2
output
30
input
4 3
output
100
input
4 0
output
4



代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;

const ll mod = 1e9+7;
const int maxn = 1e6+5;
ll f[maxn], fac[maxn];
ll pow(ll a, ll b) {                         //快速幂取模
    ll ret = 1; 
    while(b) {
        if(b&1)
            ret = (ret*a)%mod;
        a = (a*a)%mod;
        b>>=1;
    }
    return ret;
}

int main()
{
    ll n, k;
    cin>>n>>k;
    for(int i = 1; i<=k+2; i++) {            //求自然数幂和的前k+2项; 
        f[i] = (f[i-1]+pow(i*1LL, k))%mod;
    }

    if(n<=k+2) {
        cout<<f[n]<<endl;
        return 0;
    }

    fac[0] = 1;                              //求前k+2项阶乘;
    for(int i = 1; i<=k+2; i++) {
        fac[i] = (fac[i-1]*i)%mod;
    }


    ll cur = 1, ans = 0;                     //预处理分式的分子;
    for(int i = 1; i<=k+2; i++) {
        cur = (cur*(n-i))%mod;
    }

    for(int i = 1; i<=k+2; i++) {
        ll inv1 = pow(n-i, mod-2)%mod;                               //对(n-i)求逆元;
        ll inv2 = pow(fac[i-1]%mod*fac[k+2-i]%mod, mod-2)%mod;       //对阶乘求逆元;
        int sign = (k+2-i)%2?-1:1;                                   //判正负;
        ans = (ans + sign*inv1*inv2%mod*f[i]%mod*cur%mod)%mod;
    }
    ans = (ans+mod)%mod;
    cout<<ans<<endl;
    return 0;
}



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值