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
题目大意:
给定一个数字n,输出n^n的个位数字
方法一:
个位数字只与n的个位数字有关,因此每次只要乘上n的个位数字后再对10取模即可。但是本题的n较大,如果只是普通地计算幂,会超时,需要用快速幂的算法。
下面是AC代码:
//方法一:快速幂
#include <bits/stdc++.h>
using namespace std;
//x为底数,n为指数
int quick_pow(int x,long long n)
{
if(n==1) return x;
if(n%2==0) return (quick_pow(x,n/2)*quick_pow(x,n/2))%10;
else return (x*quick_pow(x,n/2)*quick_pow(x,n/2))%10;
}
int main()
{
int k;
long long n;
cin>>k;
while(k--)
{
cin>>n;
cout<<quick_pow(n%10,n)<<endl;
}
return 0;
}
方法二:
将0-9的的情况全部列出来。可以发现,最多四次就进入循环。且没有三次进入循环的,因此将n对4取模,然后输出相应的个位数字即可。
下面为AC代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int num[10][5];
//该循环用于打表
for(int i=0;i<=9;i++)
for(int j=1;j<=4;j++)
num[i][j]=(int)pow(i,j)%10;//由于pow函数返回值为double,需要用强制类型转换
long long n,k;
cin>>k;
while(k--)
{
cin>>n;
cout<<num[n%10][(n-1)%4+1]<<endl;
}
return 0;
}