HDOJ--2035--人见人爱A^B

人见人爱A^B

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


Problem Description
求A^B的最后三位数表示的整数。


说明:A^B的含义是“A的B次方”

 

Input
输入数据包括多个測试实例。每一个实例占一行,由两个正整数A和B组成(1<=A,B<=10000)。假设A=0, B=0。则表示输入数据的结束,不做处理。
 

Output
对于每一个測试实例,请输出A^B的最后三位表示的整数。每一个输出占一行。


 

Sample Input
2 3 12 6 6789 10000 0 0
 

Sample Output
8 984 1
 思路:是高速幂的,只是由于要求保留后三位。由此可知须要对高速幂进行取余操作。
ac代码:
#include<stdio.h>
int  fun(int a,int b){
    int ans=1;
    while(b){
        if(b%2)
            ans=(ans*a)%1000;//由于要保留后三位。所以知道这道题是对1000进行取余操作。 
        a=(a*a)%1000;
        b/=2;
    }
    return ans;
}
int main(){
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF&&(a||b)){
        printf("%d
",fun(a,b));
    }
    return 0;
}


原文地址:https://www.cnblogs.com/wgwyanfs/p/6932567.html