Rightmost Digit(快速幂)

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

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. 

方法一:
 #include <iostream>
using namespace std;
int a[]={,,,,,,,,,,,,,,,,,,,,};
int main()
{
int b,n;
cin>>b;
while(b--)
{
cin>>n;
cout<<a[n%]<<endl;
}
return ;
}

方法二:

 #include<stdio.h>
int my_power(int m, int n); // 求m的n次方的尾数
int main()
{
int cases, n;
scanf("%d", &cases);
while(cases--)
{
scanf("%d", &n);
printf("%d\n", my_power(n, n));
} return ;
} int my_power(int m, int n)
{
m = m%;
if(n == )
return m;
if(n% == )
return ( my_power(m*m, n/) ) % ;
else
return ( my_power(m*m, n/)*m ) % ;
}

快速幂的时间复杂度是O(logn),n = 10亿时,大约32次递归调用就能出结果,效率极大的提高了

上一篇:[POI2009]KAM-Pebbles


下一篇:transient关键字的作用