首页 > 代码库 > 1061 快速幂取模

1061 快速幂取模

 HDU 1061 Rightmost Digit
分类: ACM 算法 2011-12-17 17:37 749人阅读 评论(2) 收藏 举报
integeroutputinputeach算法c
 
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.
 
 
题意:
求n^n模10
代码:
[cpp] view plaincopy
#include<stdio.h>  
  
int exp_mod(int a,unsigned int n,int b)  
{  
    int t;  
    if(n==0||n==1)  
    return n==0?1:a;  
    t=exp_mod(a,n/2,b);  
    t=t*t;  
    if(n%2==1)t=t*a;  
    return t%b;  
}  
int main()  
{  
    int t;  
    scanf("%d",&t);  
    while(t--)  
    {  
        long long n;  
        scanf("%lld",&n);  
        printf("%d\n",exp_mod(n%10,n,10));  
    }  
    return 0;  
}  


 
分析:
代码是在网上找的模版,第一次做是想找规律的可是实在是太繁琐勒(其实是我懒= =! ),就上网看看有没有更简单的方法,才知道这样的题有模版,就是快速幂取模.果断背下来....
下面是我经过在网上找的解析:
快速幂取模就是在O(logn)内求出a^n mod b的值。算法的原理是ab mod c=(a mod c)(b mod c)mod c