C - Last Digit

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


看到这种题目,肯定想到可能会有周期,所以简单粗暴的可以打表来寻找周期。。。
果然通过打表可以发现周期是100,那么就好办了。
代码如下:
#include<stdio.h>
int main()
{
	int i,j,n,k,t,f[490][5];
    scanf("%d",&t);
    while(t--)
    {
    	scanf("%d%d",&n,&k);
       f[1][1]=1;f[1][2]=1;
	   f[1][3]=1;f[1][4]=1;	
	   for(i=2;i<=100;i++)
	   {
   		f[i][1]=(f[i-1][1]+i)%10;//printf(" %d %d ",i,f[i][1]);
   		f[i][2]=(f[i-1][2]+i*i)%10;//printf("%d ",f[i][2]);
   		f[i][3]=(f[i-1][3]%10+(i*i*i)%10)%10;//printf("%d ",f[i][3]);
   		f[i][4]=(f[i-1][4]%10+(i*i*i*i)%10)%10;//printf("%d\n",f[i][4]);
   	}
   	f[0][1]=f[100][1];
   	f[0][2]=f[100][2];
   	f[0][3]=f[100][3];
   	f[0][4]=f[100][4];
   	if(n>100)n=n%100;
   	
   	if(k>4)k=k%4;
   	if(k==0)k=k+4;
   	printf("%d\n",f[n][k]);
    }
    return 0;
}

打表的确是一种好的方法,其实还可以通过寻找循环节来做,这样就不用自己先打表找周期了。
代码二:
#include<stdio.h>
#include<string.h>
int powermod(int a,int b)
{
    int ans=1;
    a=a%10;
    while(b>0)
    {
        if(b%2==1)ans=(ans*a)%10;
        b=b/2;
        a=(a*a)%10;
    }
    return ans;
}
int main()
{
    int n,k,i,j,f[1111],T,flag,x,temp;

    scanf("%d",&T);
    while(T--)
    {    
    memset(f,0,sizeof(f));
        scanf("%d%d",&n,&k);
        for(i=1;i<=1000;i++)
        {
            f[i]=(f[i-1]+powermod(i,k))%10;
        }
        for(i=1;i<=1000;i++)
        {
            flag=1;
            for(j=i+1;j<=1000;j++)
            {
                if(f[j%i]!=f[j]){
                    flag=0;break;
                }
            }
            if(flag){
                x=i;break;
            }
        }
//        printf("%d\n",x);
    f[0]=f[x];
  temp=n%x;
        printf("%d\n",f[temp]);
    }
    return 0;
}

上述两种方法本质上都是寻找周期来解决问题。过程中要注意当n为周期的整数倍时,取模的答案是0,所以必须先f[0]=f[周期],避免出错。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值