Hdu 2685 I won't tell you this is about number theory 快速幂取模+gcd

本文探讨了一种计算特定数学表达式S=gcd(a^m-1,a^n-1)%k的方法,通过使用快速幂和辗转相除法,有效地解决了这一问题。代码实现采用C++,并提供了样例输入输出。

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

Problem Description

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

One line with a integer S.

 

 

Sample Input


 

1

1 1 1 1

 

 

Sample Output


 

0

此题需要用到一个结论....

if(a>b&&gcd(a,b)==1)

gcd(a^m-b^m,a^n-b^n)=a^gcd(m,n)-b^gcd(m,n);

代码如下:
 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long ll;
ll a,m,n,k;
int t;
ll Fast (int a,int b)
{
    ll sum=1;
    while (b)
    {
        if(b&1)
        {
            sum=sum*a%k;
        }
        b>>=1;
        a=a*a%k;
    }
    return sum;
}
ll gcd (ll a,ll b)
{
    return b==0? a:gcd(b,a%b);
}
int main()
{
    scanf("%d",&t);
    while (t--)
    {
        scanf("%lld%lld%lld%lld",&a,&m,&n,&k);
        a=a%k;
        ll ans=(Fast(a,gcd(m,n))-1+k)%k;
        printf("%lld\n",ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值