HDU - 2685 寒假训练 gcd的性质 快速幂

本文介绍了一种计算特定数学问题的方法:给定四个整数a、m、n、k,求解S=gcd(a^m-1,a^n-1)%k。通过定义gcd和power函数实现了解决方案,并给出了具体的C++代码实现。

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

To think of a beautiful problem description is so hard for me that let's just drop them off. :) 
Given four integers a,m,n,k,and S = gcd(a^m-1,a^n-1)%k,calculate the S. 

Input
The first line contain a t,then t cases followed. 
Each case contain four integers a,m,n,k(1<=a,m,n,k<=10000).
Output

Sample Input
1
1 1 1 1
Sample Output
0

代码如下

#include<iostream>
#include<math.h>
using namespace std;
typedef long long ll;
int gcd(int a,int b)
{
    while(b!=0){
        int c;
        c=a%b;
        a=b;
        b=c;
    }return a;
}
//gcd(a^m-b^m, a^n-b^n) = a^gcd(m,n)-b^gcd(m,n);这里b=1;
//gcd(a^m-1,a^n-1)=a^gcd(m,n)-1^gcd(m,n);
ll power (ll a,ll b,ll c)
{
    int ans=1;
    a=a%c;
    while(b>0)
    {
        if(b%2==1)
        {
            ans=(ans*a)%c;
        }
        b=b/2;
        a=(a*a)%c;
    }return ans;
    
}
int main()
{
    
    int t;
    ll a,m,n,k;
    cin>>t;
    while(t--)
    {
        cin>>a>>m>>n>>k;
        cout<<(power(a,gcd(m,n),k)+k-1)%k<<endl;//加k 防止出现-1
    }return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值