hdu-4704 (a^b)%c

7 篇文章 0 订阅
3 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=4704

求解(a^b)%c

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#define LL long long
#define nnum 1000005
#define nmax 31625
int flag[nmax], prime[nmax];
int plen;
void mkprime()
{
    int i, j;
    memset(flag, -1, sizeof(flag));
    for (i = 2, plen = 0; i < nmax; i++)
    {
        if (flag[i])
        {
            prime[plen++] = i;
        }
        for (j = 0; (j < plen) && (i * prime[j] < nmax); j++)
        {
            flag[i * prime[j]] = 0;
            if (i % prime[j] == 0)
            {
                break;
            }
        }
    }
}
int getPhi(int n)
{
    int i, te, phi;
    te = (int) sqrt(n * 1.0);
    for (i = 0, phi = n; (i < plen) && (prime[i] <= te); i++)
    {
        if (n % prime[i] == 0)
        {
            phi = phi / prime[i] * (prime[i] - 1);
            while (n % prime[i] == 0)
            {
                n /= prime[i];
            }
        }
    }
    if (n > 1)
    {
        phi = phi / n * (n - 1);
    }
    return phi;
}
int cmpCphi(int p, char *ch)
{
    int i, len;
    LL res;
    len = strlen(ch);
    for (i = 0, res = 0; i < len; i++)
    {
        res = (res * 10 + (ch[i] - '0'));
        if (res > p)
        {
            return 1;
        }
    }
    return 0;
}
int getCP(int p, char *ch)
{
    int i, len;
    LL res;
    len = strlen(ch);
    for (i = 0, res = 0; i < len; i++)
    {
        res = (res * 10 + (ch[i] - '0')) % p;
    }
    return (int) res;
}
int modular_exp(int a, int b, int c)
{
    LL res, temp;
    res = 1 % c, temp = a % c;
    while (b)
    {
        if (b & 1)
        {
            res = res * temp % c;
        }
        temp = temp * temp % c;
        b >>= 1;
    }
    return (int) res;
}
void solve(int a, int c, char *ch)
{
    int phi, res, b;
    phi = getPhi(c);
    if (cmpCphi(phi, ch))
    {
        b = getCP(phi, ch) + phi;
    }
    else
    {
        b = atoi(ch);
    }
    res = modular_exp(a, b, c);
    printf("%d\n", res);
}
//求解(a^b)%c;  b是大数
int main()
{
    int a, c;
    char ch[nnum];
    mkprime();
    while (~scanf("%s",ch))
    {
        int len=strlen(ch);
        int d = len-1;
        while (ch[d] == '0')
        {
            ch[d] = '9';
            d--;
        }
        ch[d]--;
        a=2;
        c=1000000007;
        solve(a%c, c, ch);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值