1347: Last Digit (周期函数)

1347: Last Digit

      Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 309     Solved: 191    


Description

    The function f(n, k) is defined by f(n, k) = 1k + 2k + 3k +...+ nk. If you know the value of n and k, could you tell us the last digit of f(n, k)?
    For example, if n is 3 and k is 2, f(n, k) = f(3, 2) = 12 + 22 + 32 = 14. So the last digit of f(n, k) 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 n, k (1 <= n, k <= 109), which have the same meaning as above.

Output

    For each test case, print the last digit of f(n, k) 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

Hint

Source

题目意思:
要你求f(n,k)函数值的最后一位
先通过快速幂得到i的k次方的最后一位
因为结果也是要你求最后一位,最后一位只能通过最后一位影响
比如i的k次方的最后一位和i+1的k次方的最后一位相加 影响的也是结果的最后一位
可以先打一个表
输出前面1000位看一下
看看能不能找到规律
然后发现果然有规律.....
其实这种题肯定是有周期性的
做多了就知道
然后就是找出周期
因为不找出周期的话,数据太太了,这提直接暴力是写不出来的
找到周期之后
n模周期就好了
这样n的大小变小了
但是n对应的值还是没有变的
周期函数嘛
code:
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<algorithm>
#include<memory.h>
#include<memory>
using namespace std;
#define max_v 1005
#define max_n 1000
typedef long long LL;
int f[max_v];
int qm(int n,int k)
{
    int ans=1;
    n=n%10;
    while(k)
    {
        if(k%2) ans=(ans*n)%10;
        k=k/2;
        n=(n*n)%10;
    }
    return ans;
}
int main()
{
    int t;
    int n,k;
    LL temp;
    scanf("%d",&t);
    while(t--)
    {
        memset(f,0,sizeof(f));
        scanf("%d %d",&n,&k);
        for(int i=1; i<max_n; i++)
        {
            temp=qm(i,k);
            f[i]=(temp+f[i-1])%10;
        }
        int flag;
        int index;
        for(int i=1; i<max_n; i++)
        {
            flag=1;
            for(int j=i+1; j<=max_n; j++)
            {
                if(f[j]!=f[j%i])
                {
                    flag=0;
                    break;
                }
            }
            if(flag)
            {
                index=i;
                break;
            }
        }
        int ans=n%index;
        printf("%d\n",f[ans]);
    }
    return 0;
}
/*
题目意思:
要你求f(n,k)函数值的最后一位

先通过快速幂得到i的k次方的最后一位
因为结果也是要你求最后一位,最后一位只能通过最后一位影响
比如i的k次方的最后一位和i+1的k次方的最后一位相加 影响的也是结果的最后一位
可以先打一个表
输出前面1000位看一下
看看能不能找到规律
然后发现果然有规律.....
其实这种题肯定是有周期性的
做多了就知道
然后就是找出周期
因为不找出周期的话,数据太太了,这提直接暴力是写不出来的
找到周期之后
n模周期就好了
这样n的大小变小了
但是n对应的值还是没有变的
周期函数嘛
*/

猜你喜欢

转载自www.cnblogs.com/yinbiao/p/9488029.html