- 快速冪求法(快速冪取模)
a,b,c || a^b%c
b若爲奇數,a^(b-1)/2
Description
給你兩個正整數N和M,求出N^M的最右邊的數字是多少。
Input
輸入包含多組測試用例,第一個行是一個整數T代表有T組測試。
接下來的T行每行包含兩個正整數N,M(1<=N,M<=1,000,000,000)由空格分開。
Output
對每組測試用例,輸出N^M最右邊的數字。
Sample Input
4
2 3
3 3
4 3
5 3
Sample Output
8
7
4
5
HINT
2^3 = 8 最右邊的數爲8
3^3 = 27 最右邊的數爲7
4^3 = 64 最右邊的數爲4
5^3 = 125 最右邊的數爲5
#include<iostream>
#include<algorithm>
using namespace std;
int fast_pow(int a,int b) //快速模冪
{
int tag=a;
int ans=1;
while(b)
{
if(b&1)
ans=(ans*tag)%10;
tag=(tag*tag)%10;
b>>=1;
}
return ans;
}
int main()
{
intn,m,t;
while(cin>>t)
{
inta[t];
for(int i=0;i<t;i++)
{
cin>>n>>m;
n=n%10;
a[i]=fast_pow(n,m)%10;
}
for(int j=0;j<t;j++)
cout<<a[j]<<endl;
}
return 0;
}