Rightmost Digit

来源:互联网 发布:淘宝发货收件人为空 编辑:程序博客网 时间:2024/06/05 13:28

题目出自于杭电oj,网址是:http://acm.hdu.edu.cn/showproblem.php?pid=1061

题目描述如下:

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
234
 

Sample Output
76
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的个位数,因此将N进行N次乘法是没有意义的,而且在物理上也是超时和超内存的,因此,我们想这道题应该会有一些规律或者是算法可循。首先我们想到的是,所求的数是个位数,这个数肯定会与N的个位数有关,而且也应该不会只与个位数相关联,那么我们首先从个位入手:

1、个位为1:

这个应该很简单,N^N的个位数也是1;

2、个位为2:

2^1=2 2^2=4 2^3=8 2^4=6 2^5=2,因此我们可以看到,二的倍数中个位数是以2、4、8、6为循环周期的,而且在本题中,以2为个位数的N肯定是偶数,因此,个位数只能为4和6,当N能被4整除的时候,个位才为6,否则为4;

3、个位为3:

3^1=3 3^2=9 3^3=7 3^4=1 3^5=3,因此3的倍数中个位数是以3、9、7、1为循环周期,与2类似,9和1去掉,尾数只能为3和7,当n%4==1时,个位为3,否则为7;

4、个位为4:

4、6、4、6,以2为周期,而且只能为偶数,所以个位为6;

5、个位为5:

个位只能为5;

6、个位为6,:

个位只能为6;

7、个位为7:

7、9、3、1,周期为4,个位只能为7和3,当n%4==1时,个位为7,否则为3;

8、个位为8:

8、4、2、6,周期为4,个位只能为4和6,当n%4==0,个位为6,否则为4;

9、个位为9:

9、1,所以个位只能为9;


所以代码如下;

#include<iostream>#include<stdio.h>using namespace std;int main(void){int T,n,sd,digit;scanf("%d",&T);while(T--){if(scanf("%d",&n) != EOF){sd = n%10;if(sd==0 || sd==1 || sd==5 || sd==6 || sd==9)digit = sd;else if(sd == 2 || sd == 8){if(n%4 == 0)sd = 6;elsesd = 4;}else if(sd == 3){if(n%4 == 1)sd = 3;elsesd = 7;}else if(sd == 4){sd = 6;}else{if(n%4 == 1)sd = 7;elsesd = 3;}printf("%d\n",sd);}}return 0;}

0 0
原创粉丝点击