题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1061
Rightmost Digit
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.
快速幂用于求解x的n次方,n非常大 直接乘会超时的。把n分解 表示成二进制原理的形式—2^k1 + 2^k2 + 2^k3....
&运算通常用于二进制取位操作,例如x&1就是取二进制的最末位。(还可以判断奇偶性,x&1==0为偶,x&1==1为奇)。>>运算用于二进制去掉最后一位。
11的二进制表示为1011,a^11=a^(2^0)*a^(2^1)*a^(2^3)=a^(2^0+2^1+2^3)
#include<iostream>
using namespace std;
typedef long long ll;
ll mod_pow(ll base,ll n,ll mod) //计算base^n
{
ll ans=1;
ll mul=base;
while(n)
{
if(n&1)
{
ans=ans*mul;
}
ans%=mod;//一般由于数太大要取模。
mul*=mul;
mul%=mod;
n>>=1;//或者n/=2,再取一位。
}
return ans;
}
int main(){
ll n;
int T;
cin>>T;
while(T--){
cin>>n;
cout<<mod_pow(n,n,10)<<endl;
}
return 0;
}