CodeForces_1732A

这篇博客探讨了如何利用欧几里得算法(gcd)解决编程问题,证明了gcd(a, a+1) = 1的性质,并展示了如何在C++中实现该算法。通过实例,解释了如何找到一组操作,使得数组中所有元素的最大公约数为1或特定值。

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

链接

思路

利用到了 g c d ( a ,   a + 1 ) = 1 gcd(a,\ a+1) =1 gcd(a, a+1)=1 ,这一个性质。

证明:

原式 = g c d ( a , a + 1 ) = gcd(a,a+1) =gcd(a,a+1)

= g c d ( a + 1 , a ) =gcd(a+1,a) =gcd(a+1,a)

= g c d ( a , 1 ) =gcd(a,1) =gcd(a,1)

= 1 =1 =1

代码

// #pragma GCC optimize(3)
#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <string>
#include <cstdio>
#include <bitset>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
#define endl '\n'
#define fi first
#define se second
#define PI acos(-1)
#define LL long long
#define INF 0x3f3f3f3f
#define lowbit(x) (-x&x)
#define PII pair<int, int>
#define ULL unsigned long long
#define PIL pair<int, long long>
#define mem(a, b) memset(a, b, sizeof a)
#define rev(x) reverse(x.begin(), x.end())
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)

using namespace std;

const int N = 25;

int n;
int a[N];
int g;

int gcd(int a, int b) {
	return b ? gcd(b, a % b) : a;
}

void solve() {
	int tt = 1;
    cin >> tt;
    while (tt -- ) {
    	cin >> n >> g;
    	for (int i = 1; i < n; i ++ ) {
    		cin >> a[i];
    		g = gcd(g, a[i]);
    	}
    	
    	if (g == 1) cout << 0 << endl;
    	else if (gcd(g, n) == 1) cout << 1 << endl;  // 对最后一个操作
    	else if (gcd(g, n - 1) == 1) cout << 2 << endl;  // 对倒数第二个操作
        //对最后两个操作,用到上面的性质
    	else if (gcd(gcd(g, n), n - 1) == 1) cout << 3 << endl;  
    }
}

int main() {
	IOS;
	
	solve();
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值