Last Digit 快速幂 取余

   The function f(nk) is defined by f(nk) = 1k + 2k + 3k +...+ nk. If you know the value of n and k, could you tell us the last digit of f(nk)?
    For example, if n is 3 and k is 2, f(nk) = f(3, 2) = 12 + 22 + 32 = 14. So the last digit of f(nk) is 4.

Input

    The first line has an integer T (1 <= T <= 100), means there are T test cases.
    For each test case, there is only one line with two integers nk (1 <= nk <= 109), which have the same meaning as above.

Output

    For each test case, print the last digit of f(nk) in one line.

Sample Input

10
1 1
8 4
2 5
3 2
5 2
8 3
2 4
7 999999997
999999998 2
1000000000 1000000000

Sample Output

1
2
3
4
5
6
7
8
9
0
求前n个数阶乘的和的个上的数。直接求和与幂,数据太大,无法容纳,
利用公式(a+b)%m=(a%m+b%m)%m  (a*b)%m=(a%m*b%m)%m
就可以将数据存储,而且还要用快速幂提高求幂效率。
#include<bits/stdc++.h>
using namespace std;
int vc[110];
int mypow(int a,int b)
{
    int ans=1,temp=a;
    while(b)
    {
        if(b&1){
            ans*=temp;
            ans%=10;
        }
        temp*=temp;
        temp%=10;
        b>>=1;
    }
    return ans%10;
}
/**/
int main()
{
    int t;cin>>t;
    while(t--)
    {
        int a,b;scanf("%d%d",&a,&b);
        int ans=0;
        for(int i=1;i<=100;i++)
        {
            ans+=mypow(i,b);
            ans%=10;
            vc[i]=ans;
        }printf("%d\n",vc[a%100]);
    }
}

猜你喜欢

转载自blog.csdn.net/Cworld2017/article/details/81740598