C - Last Digit

来源:互联网 发布:abb机器人离线编程软件 编辑:程序博客网 时间:2024/05/16 15:29

Description

    The functionf(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 off(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 off(n, k) is 4.

Input

    The first line has an integerT (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 off(n, k) in one line.

Sample Input

101 18 42 53 25 28 32 47 999999997999999998 21000000000 1000000000

Sample Output

1234567890看到这种题目,肯定想到可能会有周期,所以简单粗暴的可以打表来寻找周期。。。果然通过打表可以发现周期是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
原创粉丝点击