FZU 1650 1752 a^b mod c

Accept: 822    Submit: 3560
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem Description

Given A,B,C, You should quickly calculate the result of A^B mod C. (1<=A,B,C<2^63).

 Input

There are multiply testcases. Each testcase, there is one line contains three integers A, B and C, separated by a single space.

 Output

For each testcase, output an integer, denotes the result of A^B mod C.

 Sample Input

3 2 42 10 1000

 Sample Output

124
这题因为数据比较大,直接用快速幂模板会超unsigned long long 范围,所以用同 样的思想计算a*b/%c.可以看做模板。输入用%llu 或%I64u.   
#include<stdio.h>
#include<string.h>
#define ll unsigned __int64
ll mul(ll a,ll b,ll c)   //用快速幂的思想求a*b%c防止越界  
{    
    ll ret=0,tmp=a%c;    
    while(b)    
    {    
        if(b&1)    
            if((ret+=tmp)>=c)    
                ret-=c;    
        if((tmp<<=1)>=c)    
            tmp-=c;    
        b>>=1;    
    }     
    return ret;    
}  

ll f(ll a,ll b,ll c)
{
	ll ans=1;
	a=a%c;
	while(b>0){
		if(b%2==1){
			ans=mul(ans,a,c);
		}
		b=b/2;
		a=mul(a,a,c);
	}
	return ans;
}


int main()
{
	ll n,m,i,j,a,b,c;
	while(scanf("%I64u%I64u%I64u",&a,&b,&c)!=EOF)
	{
		printf("%I64u\n",f(a,b,c));
	}
	return 0;
}

posted @ 2015-08-03 16:45  Herumw  阅读(169)  评论(0编辑  收藏  举报