首页 > 其他 > 详细

FZU1752 A^B mod C

时间:2020-04-23 01:56:32      阅读:84      评论:0      收藏:0      [点我收藏+]

技术分享图片 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 4
2 10 1000

技术分享图片 Sample Output

1
24
#include <iostream>
#include <stdio.h>
using namespace std;
typedef long long LL;

/*
    这道题有个大坑 如果直用快速幂 LL会爆 必须配合快速乘 其中快速乘如果%=还是会超时 使用-=会快点
    思路:快速幂+快速乘
*/

//快速乘
LL quickMul(LL a, LL b, LL mod) {
    LL res = 0;
    while (b)
    {
        if (b & 1) {
            res += a;
            //注意%= 还得用快速求余  于是干脆用-=
            if (res >= mod)
                res -= mod; //大于减mod
        }
        a <<= 1;
        if (a >= mod)
            a -= mod;
        b >>= 1;
    }
    return res;
}

//快速幂
LL quickPow(LL a, LL b, LL mod)
{
    LL res = 1;
    a %= mod;
    while (b)
    {
        if (b & 1) {
            res = quickMul(res, b, mod);
        }
        b >>= 1;
        a = quickMul(a, a, mod);
    }
    return res;
}

int main()
{
    LL a, b, c, res;
    while (~scanf("%I64d%I64d%I64d", &a, &b, &c))
    {
        //注意快速幂 以及LL的时候快速乘
        a %= c;
        res = 1;
        while (b)
        {
            if (b & 1)
                res = quickMul(res, a, c);
            b = b >> 1;
            a = quickMul(a, a, c);
        }
        printf("%I64d\n", res);
    }
}
 

FZU1752 A^B mod C

原文:https://www.cnblogs.com/dlvguo/p/12757610.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!