HDU 1061 [Rightmost Digit] 规律

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1061

题目大意:求N^N的个位数

关键思想:对1个N来说,乘方时末尾会循环。对所有N来说,结果以20为周期。

代码如下(第一种方法:循环节):

#include <iostream>
#include <cmath>
using namespace std;

int main(){
    int T,i,cnt,m;//cnt为循环节长度,m为每次(乘的尾数) 
    long long N;
    cin>>T;
    while(T--){
        cin>>N;
        if(N%10==0){
            cout<<0<<endl;
            continue;
        }
        int t[21]={0};
        bool v[10]={false};  //记录是否出现过下标数字 
        cnt=1,i=m=N%10;
        while(!v[i]){
            t[cnt++]=i;
            v[i]=true;
            i*=m;
            i%=10;
        }
        cout<<t[N%(cnt-1)==0?cnt-1:N%(cnt-1)]<<endl;//因为t[0]未使用 
    }
    return 0;
}

  

 (第二种方法:打表)

//可以发现,N的幂的个位数周期为4.所以关键就是看N%10和N%4的值,而他们的最小公倍数是20,所以周期是20
#include <stdio.h>
#include <cmath>
int num[20] = {0,1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9};

int main()
{
	int C;
	int n;
	scanf("%d", &C);
	while(C--)
	{
		scanf("%d", &n);
		printf("%d\n", num[n % 20]);
	}
}

  

posted @ 2017-03-06 22:25  哇咔咔咔  阅读(117)  评论(0编辑  收藏  举报