1681.easy problem Ⅱ

本文介绍了一种计算2^N-1与2^M-1最大公约数的有效算法,并提供了完整的AC代码实现。该算法避免了直接计算大整数带来的溢出问题,采用递归求解最大公约数的方法。

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

Description

请计算对于给出的N,M,2N-1与2M-1的最大公约数。

多组测试用例

Input

两个整数N,M(1 <= N <= 100, 1<= M <= 100)

Output

2^N-1与2^M-1的最大公约数,保证结果不超过2^63-1(此处”^"均不是异或,而是次幂的意思)

Sample Input

1 2

Sample Output

1 

注意:输出2的gcd(n,m)次幂后减1就行,直接求会爆long long

附上AC代码:

#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <utility>
#include <iostream>
#include <algorithm>
using namespace std;

#define ll long long

int main()
{
	ll a,b;
	ll gcd(ll x, ll y);
	ll q_pow(ll a, ll b);
	int n,m;
	
	
    while(cin>>n>>m)
    {
    	a=gcd(n,m);
    	b=q_pow(2,a)-1;//不要分别求2的m次幂和2的n次幂,会爆long long
    	printf("%lld\n",b);
	}
	return 0;
}

ll gcd(ll x, ll y)
{
    if(x%y == 0)return y;
  	return gcd(y, x%y);
}

ll q_pow(ll a, ll b)
{
    ll ans = 1;
    while(b > 0)
	{
	    if(b & 1)
		ans = ans * a ;
	    a = a * a ;
	    b >>= 1;
    }
    return ans;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值