EOlymp - 1121 (GTMD快速乘)

本文介绍了一种处理大数幂取模运算的有效算法,针对输入的三个整数a、b、c,求解a的b次方再模c的问题。通过使用快速乘法和快速幂算法,避免了直接计算过程中的数据溢出,适用于处理大范围内的数值运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 #1
3 2 4
2 10 1000
Output example #1
1
24

数据相乘爆long long,用快速乘。

当然了还有更巧妙的奇淫巧计:

long long ksc(long long x,long long y,long long mod)
{
    long long z=(long double)x/mod*y;
    long long res=(usigned long long)x*y-(usigned long long)z*mod;
    return (res+mod)%mod;
}

// 一种自动溢出的数据类型(存满了就会自动变为0)

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
#include <string>

using namespace std;
//for(i=1;i<n;i++)
//scanf("%d",&n);
//printf("\n",);

long long tree[400000],c;

long long f(long long a,long long b)
{
    long long temp=0;

    while(b!=0)
    {
        if(b%2==1)
        {
            temp+=a;
            temp%=c;
        }
        a+=a;
        a%=c;
        b>>=1;
    }
    return temp;
}

int main()
{
    long long i,j,k,a,b;

    while(scanf("%lld%lld%lld",&a,&b,&c)!=EOF)
    {
        a%=c;
        k=1;
        while(b!=0)
        {
            if(b%2==1)
            {
                k=f(k,a);
                k%=c;
            }

            a=f(a,a);
            a%=c;
            b>>=1;
        }
        printf("%lld\n",k);
    }


//memset(num,0,sizeof(num));
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值