杭电1061 Rightmost Digit

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.
解题思路:
乍一看这个题,再对比之前的大数相乘,很容易想成大数相乘的题。但是仔细一看,发现其实是有规律的。
想一下,因为是乘法,而且是n个相同的数相乘,所以只有最后一位数才是参与运算的,这样一看就不难发现是有规律的了。
动手写一下即可发现其中的规律(n个末位一样的数求乘法):
0 0 这个地方千万不要忘记0的存在,因为会有20^20
1 1
2 2 4 8 6
3 3 9 7 1
4 4 6
5 5
6 6
7 7 9 3 1
8 8 4 2 6
9 9 1
下面先上一份比较容易理解的代码,用枚举法列出所有可能的情况:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
int main()
{
 	int T,n;
	scanf("%d",&T);
	while(T--)
	{
		
		scanf("%d",&n);
		if(n == 0)
		return 0;
		if(n % 10 == 0)
		printf("0\n");
		if(n % 10 == 1)
		printf("1\n");
		if(n % 10 == 2)
		{
			if(n % 4 == 0)
			printf("6\n");
			if(n % 4 == 1)
			printf("2\n");
			if(n % 4 == 2)
			printf("4\n");
			if(n % 4 == 3)
			printf("8\n");
		}
		if(n % 10 == 3)
		{
			if(n % 4 == 0)
			printf("1\n");
			if(n % 4 == 1)
			printf("3\n");
			if(n % 4 == 2)
			printf("9\n");
			if(n % 4 == 3)
			printf("7\n");
		}
		if(n % 10 == 4)
		{
			if(n % 2 == 0)
			printf("6\n");
			if(n % 2 == 1)
			printf("4\n");
		}
		if(n % 10 == 5)
		{
			printf("5\n");
		}
		if(n % 10 == 6)
		{
			printf("6\n");
		}
		if(n % 10 == 7)
		{
			if(n % 4 == 0)
			printf("1\n");
			if(n % 4 == 1)
			printf("7\n");
			if(n % 4 == 2)
			printf("9\n");
			if(n % 4 == 3)
			printf("3\n");
		}
		if(n % 10 == 8)
		{
			if(n % 4 == 0)
			printf("6\n");
			if(n % 4 == 1)
			printf("8\n");
			if(n % 4 == 2)
			printf("4\n");
			if(n % 4 == 3)
			printf("2\n");
		}
		if(n % 10 == 9)
		{
			if(n % 2 == 0)
			printf("1\n");
			if(n % 2 == 1)
			printf("9\n");
		}
	} 
 	return 0;
}

下面说另外一种解题思路:
因为只是最后一位有用,所以只把最后一位提取出来。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<ctype.h>
int main()
{
	int T,n,m,k,i,s;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		m = n % 4;  //因为最多四个一循环,所以取4的余 
		k = n % 10;
		if(m == 0)  //如果n为0的话,相当于是最后一个,无法进行后面的乘法循环,所以变为4 
		m = 4;
		s = 1;
		for(i = 0;i < m;i++)
		{
			s = s * n % 10;
		}
		printf("%d\n",s);
	}
 	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值