您的位置:首页 > 其它

杭电--1061 Rightmost Digit

2017-04-11 19:26 531 查看
本题连接:点击打开链接

Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 55381    Accepted Submission(s): 20938


[align=left]Problem Description[/align]
Given a positive integer N, you should output the most right digit of N^N.

 

[align=left]Input[/align]
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).

 

[align=left]Output[/align]
For each test case, you should output the rightmost digit of N^N.

 

[align=left]Sample Input[/align]

2
3
4

 

[align=left]Sample Output[/align]

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.

 

[align=left]Author[/align]
Ignatius.L
 

[align=left]Recommend[/align]
We have carefully selected several similar problems for you:  1071 1425 1060 1205 1042 
 

题意:先输入一个整数T,表示有T组测试数据,接下来给出一个数N(1<=N<=1,000,000,000),求该数的N次幂的个位是多少?

 

思路一:对于这一类涉及到大数,而要求的结果又比较简单,我在hdu--1005中就说过应该首先就要想到的是找规律,打个表观察一下,找出它的周期就好了,通常都是可以的。

 

代码一:

#include <iostream>
#include <cstdio>
using namespace std;
/*void fun()        //找出50以内的整数的N的N次方的个位数。
{
for(int i=1; i<50; i++)
{
int a=i;
for(int j=1; j<i; j++)  //注意循环次数
{
a=(a*i)%10;
}
printf("%d\t",a);
}
printf("\n************\n");
}*/
int main()
{
//fun();        //打表找规律
int t;
scanf("%d",&t);
while(t--)
{
int n,i,p;
scanf("%d",&n);
n=n%20;             //周期为20
p=n;
for(i=1; i<n; i++)
p=(n*p)%10;
printf("%d\n",p);
}
return 0;
}

 

思路二:由于只要求个位数,所以有种方法很适用这个题,那就是快速幂取余(详解请点http://www.phpstudy.net/b.php/67443.html)。

快速幂算法明显依赖于以下公式:



快速幂取余代码如下:

int QY(int a,int b,int c)   //求 a 的 b 次幂对 c 取的余数
{
int k=1;   		 //记录结果
a=a%c;      		 //预处理一下,使a比c小
while(b)
{
if(b%2==1)        //公式使用
k=(k*a)%c;
b=b/2;
a=(a*a)%c;
}
return k;
}

 

本题代码二:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int qky(int a)
{
int k=1;
int b=a;
a=a%10;         //本题对10取余,且为本身的次幂
while(b)
{
if(b%2==1)
k=(k*a)%10;
b/=2;
a=(a*a)%10;
}
return k;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
printf("%d\n",qky(n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM 杭电 快速幂取余