Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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).
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 6HintIn 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%10)^N )%10;所以关键就在这个快速幂算法了;
直接上代码:
#include<bits/stdc++.h>
using namespace std;
int fast(int x)
{
int s=1,xx=x;
x%=10;
while(xx)//快速幂取余核心问题;
{
if(xx&1)
s=(s*x)%10;
x=x*x%10;
xx=xx>>1;
}
return s;
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
if(n%10==0)
printf("0\n");
else
printf("%d\n",fast(n));
}
return 0;
}