hdu 1061 Rightmost Digit (模幂运算)

题目:

Rightmost Digit

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18913    Accepted Submission(s): 7266

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
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.

(这是一道非常经典的模幂运算的题目。只要模幂运算的那些理论真正弄懂啦,这种类型的题目就不难。理论方面,我的一篇博客有详细介绍。题意很简单,就不翻译啦。。)

下面是AC的具体代码:

#include <stdio.h>
int main()
{
    int T,a,i,j;
    scanf("%d",&T);
    for(i=0;i<T;i++)
    {
        int x,n,p,res;
        x=0,n=0,p=10;//理论:(x^n) % p = ((x % p)^n) % p,给题目赋个初值
        scanf("%d",&a);
        x =a%p,n=a,res=1;
        while(n){//设置循环结束条件:n=0
            if(n%2!=0)//判断指数的奇偶性
                res=(res*x)%p;//写成这样会更好理解点:res*=x; res%=p;
            x=x*x;//下面这三条语句的目的是缩小范围,即:((x*x)^[n/2]) % p(这是n为偶数情况),这里要注意,要判断n的奇偶性,如果n是奇数:(x*(x*x)^[n/2]) % p
            x=x%p;
            n=n/2;//幂减半
        }
        printf("%d\n",res);
    }
    return 0;
}

你可能感兴趣的:(Integer,input,each,output)