HDU-1061

杭電1061 簡單題

題目:

Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 85186    Accepted Submission(s): 31372


 

Problem Description
Given a positive integer N, you should output the most right digit of N^N.
 

 

Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
 

 

Output
For each test case, you should output the rightmost digit of N^N.
 

 

Sample Input

 
2 3 4
 

 

Sample Output

 
7 6
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7. In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.
 

 

Author
Ignatius.L
 

題意:求n的n次方的個位數,n最大有1000000000(明顯要找規律)

題解:求個位數實際就是n的個位數相乘,這個規律不難找1,5,6,0無論多少個相乘都是自身,4奇數個相乘個位爲4,偶數個爲6,9對應9,1,其次2,3,7,8都有int a[5][5] = {{2,4,8,6}, {3,9,7,1},{7,9,3,1},{8,4,2,6}};,再總結一下就是四個一循環(公共最小公倍數如1,1,1,1也算四個一循環)

代碼1(笨辦法,分情況討論,細節要處理好):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int a[5][5] = {{2,4,8,6}, {3,9,7,1},{7,9,3,1},{8,4,2,6}};

int main()
{
	int t, i, j, ans, n, m;
	scanf("%d", &t);
	while(t--){
		scanf("%d", &m);
		n = m%10;
		if(n==6||n==1||n==5||n==0){
			ans = n;
		}
		if(n==4||n==9){
			i = m%2; //一直w,後來發現我這個地方搞錯了,之前一直用的n,也就是取餘後的數,難受
			if(i==0){
				if(n==4) ans = 6;
				if(n==9) ans = 1;
			} else{
				ans = n;
			}

		}
		if(n==2||n==3||n==7||n==8){
			if(n==2) i=0;
			if(n==3) i=1;
			if(n==7) i=2;
			if(n==8) i=3;
			j = (m-1)%4;
			ans = a[i][j];
		}
		printf("%d\n", ans);
	}
	return 0;
}

代碼2(四個一循環):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
	int t, i, j, ans, n;
	scanf("%d", &t);
	while(t--){
		scanf("%d", &n);
		i = n%4;
		n = n%10;
		if(i==0) i = 4;
		ans = (int)pow(n,i)%10;
		printf("%d\n",ans);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章