A^B mod C(快速幂+快速乘)

A^B mod C(快速幂+快速乘)

Description:

Given a, b, c find the value of ab mod c (1 ≤ a, b, c < 263).

Input
Contains multiple test cases. Each test is given in one line and contains three integers a, b and c.

Output
For each test case print on a separate line the value of ab mod c.

Example 1
Input example
3 2 4
2 10 1000
Output example
1
24

题解:直接用快速幂数据范围会超过long long(就是底数相乘还没来的及取模就已经超了),所以要用到快速乘把乘法运算化成加法运算,在运算过程中每加一次取一次模就能避免数据超出范围;

AC代码:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
using namespace std;

long long fast_mul(long long a,long long b,long long mod)
{
    long long ans=0;
    while(b)
    {
        if(b&1)
            ans=(ans+a)%mod;
        a=(a+a)%mod;
        b>>=1;
    }
    return ans;
}

long long fast_pow(long long a,long long b,long long mod)
{
    long long ans=1;
    while(b)
    {
        if(b&1)
            ans=fast_mul(ans,a,mod);
        a=fast_mul(a,a,mod);
        b>>=1;
    }
    return ans;
}
int main()
{
    long long a,b,c;
    while(~scanf("%lld%lld%lld",&a,&b,&c))
        printf("%lld\n",fast_pow(a,b,c));
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值