Rightmost Digit (求n^n最后一位)

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.

 

n^n最后一位,等价于(n%100)^(n%100)的最后一位。

 1 #include<cstdio>
 2 int main()
 3 {
 4     __int64 t,l,b;
 5     scanf("%I64d",&t);
 6     while(t--)
 7     {
 8         __int64 n;
 9         scanf("%I64d",&n);
10             l=n%100;
11             b=l;
12             for(__int64 i=1;i<l;i++)
13             {
14                 b=b*l;
15                 b%=100;
16             }
17             b%=10;
18             printf("%I64d\n",b);
19     }
20 }

 快速幂

 

快速幂求n^n;

 

 1 int f1(int a,int b)
 2 {
 3     int t=1;
 4     while(b)
 5     {
 6         if(b % 2 != 0)
 7         {
 8             t*=a;
 9             b--;            
10         }
11         a*=a;
12         b/=2;
13     }
14     return t;
15 }

 

快速幂求n^n后y位;

 

 1 int f2(int a,int b)
 2 {
 3     int t=1;
 4     while(b)
 5     {
 6         if(b % 2 != 0)
 7         {
 8             t=(t*a)%x;    //x控制要求的位数 
 9             b--;
10         }
11         a=(a*a)%x;
12         b/=2;
13     }
14     return t;
15 }

 

代码

 1 #include<cstdio>
 2 __int64 f(__int64 a)
 3 {
 4     __int64 b=a;
 5     __int64 t=1;
 6     while(b)
 7     {
 8         if(b%2!=0)
 9         {
10             t=(t*a)%10;
11             b--;
12         }
13         a=a*a%10;
14         b/=2;
15     }
16     return t;
17 }
18 int main()
19 {
20     __int64 t,a;
21     scanf("%I64d",&t);
22     while(t--)
23     {
24         scanf("%I64d",&a);
25         printf("%I64d\n",f(a));
26     }
27 }

 

posted @ 2016-07-22 18:31  野小子&  阅读(800)  评论(0编辑  收藏  举报