FZU1759 Super A^B mod C(快速幂求余+ a^b%c = a^( b%phic+phic )%c)

 Problem 1759 Super A^B mod C

Accept: 596    Submit: 2010
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,C<=1000000000,1<=B<=10^1000000).

 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 4 2 10 1000

 Sample Output

1 24

 

求解a^b%c,因为b的数值太大,只能使用公式转换 a^b%c = a^( b%phic+phic )%c;

只要求出phic后就可以将b转化为一个可以存下的整数,然后使用快速幂,就可以求解出结果。

不要有一个要注意,就是这个公式使用的条件,那就是 b > phic ,所以要先判断 b的大小

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define LL __int64
char s[1100000] ;
LL getphi(LL n)
{
    LL ans = n , m = (LL)sqrt(n+0.5);
    LL i , j ;
    for(i = 2 ; i <= m ; i++)
    {
        if( n%i == 0 )
        {
            ans = ans / i * (i-1) ;
            while( n%i==0 )
                n /= i ;
        }
    }
    if( n > 1 )
        ans = ans / n * (n-1);
    return ans ;
}
LL pow_mod(LL a,LL b,LL c)
{
    if( b == 0 )
        return 1 ;
    LL ans = pow_mod(a,b/2,c);
    ans = ans * ans %c ;
    if( b%2 )
        ans = ans*a%c;
    return ans;
}
int main()
{
    LL a , c , i , l , phic , b ;
    while(scanf("%I64d %s %I64d", &a, s, &c)!=EOF)
    {
        l = strlen(s);
        phic = getphi(c);
        if( l < 10 )
        {
            b = 0 ;
            for(i = 0 ; i < l ; i++)
                b = b*10 + (s[i] -'0');
            printf("%I64d\n", pow_mod(a,b,c));
            continue ;
        }
        b = (s[0] - '0')%phic ;
        for(i = 1 ; i < l ; i++)
        {
            b %= phic ;
            b = ( b*10 + s[i]-'0' )%phic ;
        }
        b += phic ;
        printf("%I64d\n", pow_mod(a,b,c) );
    }
}


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值