LeetCode-1250.检查好数组

题目:
在这里插入图片描述
代码:(根据数学知识可知只需要所有数的最大公约数为1即可!)

class Solution {
public:
    int gcd(int a,int b){
        if(a==0||b==0) return a+b;
       // if(a==1||b==1) return 1;
        if(a==b) return a;
        if(a>b) return gcd(b,a%b);
        return gcd(a,b%a);
    }
    bool isGoodArray(vector<int>& nums) {
        int n=nums.size();
        if(n==0||(n==1&&nums[0]!=1)) return false;
        if(n==1) return true;
        int g=nums[0];
        int temp;
        for(int i=1;i<n;i++){
            temp=gcd(g,nums[i]);
            if(temp==1) return true;
            g=temp;
        }
        return false;
    }
};

榜首代码:

/*
本题考查数学定理-
对于n个正整数a1, a2, ..., an,其最大公约数为g,
那么,必然存在n个整数,x1, x2, ..., xn使得
{x1, x2, ..., xn} x {a1, a2, ..., an} = d
如果d为1,那么就符合这道理的要求。
即判断数组中所有元素的最大公约数是否为1
*/
static const auto io_speed_up = []() {
	std::ios::sync_with_stdio(false);
	cin.tie(nullptr);
	return 0;
}();
class Solution {
public:
    bool isGoodArray(vector<int>& nums) {
        int N = nums.size();
        if(N < 2){
            return N == 1 && nums[0] == 1;
        }
        int g = gcd(nums[0], nums[1]);
        for(int i = 2; i < N && g != 1; ++i){
            g = gcd(g, nums[i]);
        }
        return g == 1;
    }

private:
    int gcd(const int &m, const int &n){
        return n == 0 ? m : gcd(n, m % n);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值