【拉格朗日求自然数幂和】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
    评论
拉格朗日乘子法可以用来解约束最优化问题,其中Ri和Ti是未知的优化变量,而约束条件则可以用等式或不等式来表示。 假设我们要解的问题可以表示为如下形式: minimize f(Ri, Ti) subject to g(Ri, Ti) = 0 其中,f(Ri, Ti)是我们要最小化的目标函数,g(Ri, Ti) = 0是一个约束条件。使用拉格朗日乘子法,我们可以将原问题转化为一个无约束的优化问题。 首先,我们定义拉格朗日函数L(Ri, Ti, λ)为: L(Ri, Ti, λ) = f(Ri, Ti) + λg(Ri, Ti) 其中,λ是拉格朗日乘子。然后,我们可以通过解以下方程组来解Ri、Ti和λ: ∂L/∂Ri = 0 ∂L/∂Ti = 0 ∂L/∂λ = 0 通过解这个方程组,我们可以得到Ri、Ti和λ的值。其中,λ的值可以用来检验我们得到的解是否满足约束条件。如果λ的值为0,则表示约束条件已经满足。 在具体实现时,可以使用MATLAB的fmincon函数来进行解。该函数可以通过设置约束条件和目标函数来解最优化问题。例如,我们可以使用以下代码来解Ri和Ti: ```matlab % 定义目标函数 fun = @(x) x(1)^2 + x(2)^2; % 定义约束条件 nonlcon = @(x)deal([], [x(1)^2 + x(2)^2 - 1]); % 使用fmincon函数解最优化问题 [x, fval] = fmincon(fun, [0 0], [], [], [], [], [], [], nonlcon); ``` 在上面的代码中,我们定义了一个目标函数f(x) = x1^2 + x2^2,其中x是一个2维向量,表示Ri和Ti。我们还定义了一个约束条件,即x1^2 + x2^2 = 1。然后,我们使用fmincon函数来解最优化问题,得到最优解x和最小化的目标函数值fval。 需要注意的是,上面的代码只是一个简单的例子,实际问题可能更加复杂,需要根据具体情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值