Summing up Powers LightOJ

来源:互联网 发布:javascript是基于对象 编辑:程序博客网 时间:2024/05/23 15:06

Given N and K, you have to find

(1^K + 2^K + 3^K + … + N^K) % 2^32

Input
Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case contains two integers N (1 ≤ N ≤ 10^15) and K (0 ≤ K ≤ 50) in a single line.

Output
For each case, print the case number and the result.

Sample Input
3
3 1
4 2
3 3
Sample Output
Case 1: 6
Case 2: 30
Case 3: 36

思路:假设f(n)=1^K + 2^K + 3^K + … + N^K,那么f(n+1)=f(n)+(n+1)^K。用二项式定理展开得到:
f(n+1)=f(n)+C(k,0)*x^k+C(k,1)*x^(k−1)+⋯+C(k,k)*x^0.
这里写图片描述
然后%2^32就是uint的自然溢出

代码如下

#include <iostream> #include <cstring>#include <cstdio>using namespace std; #define LL long long const int mod=1000000007; typedef unsigned int uint; //mod 2^32就是uint的自然溢出uint C[55][55];int f;struct matrix{    uint x[55][55];};matrix mutimatrix(matrix a,matrix b){    matrix temp;     memset(temp.x,0,sizeof(temp.x));        for(int i=0;i<=f+1;i++)    for(int j=0;j<=f+1;j++)    for(int k=0;k<=f+1;k++)    {        temp.x[i][j]+=a.x[i][k]*b.x[k][j];        //temp.x[i][j]%=mod;    }    return temp;}matrix k_powmatrix(matrix a,LL n)//矩阵快速幂{    matrix temp;    memset(temp.x,0,sizeof(temp.x));    for(int i=0;i<=f+1;i++)    temp.x[i][i]=1;    while(n)    {        if(n&1)        temp=mutimatrix(temp,a);        a=mutimatrix(a,a);        n>>=1;    }    return temp;} void ini(){    C[1][1] = 1;    for(int i = 1; i <= 50; ++i) C[i][0] = 1;    for(int i = 2; i <= 50; ++i)        for(int j = 1; j <= i; ++j)            C[i][j] = C[i-1][j] + C[i-1][j-1];}int main(){    ini();//对组合数预处理    int T;    LL n;    scanf("%d",&T);    for(int cas=1;cas<=T;cas++)    {        scanf("%lld%d",&n,&f);        if(f==0)//注意当f(即k)为0时,特殊判断下        {            printf("Case %d: %u\n",cas,n);            continue;        }        matrix st;        memset(st.x,0,sizeof(st.x));        st.x[0][0]=1;        st.x[f+1][f+1]=1;        for(int i=1;i<=f+1;i++)        st.x[i][0]=C[f][i-1];        for(int j=1;j<=f;j++)        for(int i=j;i<=f+1;i++)        st.x[i][j]=C[f-j+1][i-j];         matrix init;//初始矩阵        //memset(init.x,0,sizeof(init.x));        for(int i=0;i<=f+1;i++)        init.x[0][i]=1;        st=k_powmatrix(st,n-1);//经过n-1次相乘        st=mutimatrix(init,st);//然后再乘上初始矩阵        printf("Case %d: %u\n",cas,st.x[0][0]);    }    return 0; }