Thursday, July 29, 2010

ACM-374 Big Mod with C++



/********************************/
/* This program is used to */
/* calculate */
/* R = B^P mod M */
/********************************/


#include <iostream>
#include <ctype.h>
#include <cstdio>
#include <math.h>

using namespace std;
long long M;
long long ans_power(long long a ,long long b);


int main(int argc, char* argv[])
{
long long B,P;
long long res;

while(cin>>B>>P>>M)
{
if(M == 1)
{
res = 0;
}
else if(B == 0 && P == 0) //0^0 = 1
{
res = 1;
}
else if(B == 0 && P != 0) //0^n = 0
{
res = 0;
}
else if(B != 0 && P == 0) //n^0 = 1
{
res = 1;
}
else
{
res = ans_power(B,P) % M;
}
cout<<res<<endl;
}
return 0;
}


long long ans_power(long long a ,long long b)
{
if (b == 0)
{
return 1;
}
else if ((b % 2) == 1)
{
long long foo = ans_power(a, (b/2));
return ((foo * foo * a) % M);
}
else
{
long long foo = ans_power(a, (b/2));
return ((foo * foo) % M);
}
}



本來用for迴圈做

也是吃了TLE

決定切開來mod這樣比較快

不然本來2的300次方

迴圈跑300次

切開之後變成超省時

No comments: