求一个数组的最大公约数和最小公倍数

求一个数组的最大公约数

可以先选择前2个数求出他们的最大公约数,然后遍历数组,依次把最大公约数和数组元素求最大公约数,当局部最大公约数为1时,返回1即可。

#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

//减法
int gcb(int a,int b)
{
    if(a<b)
        swap(a,b);
    else if(a==b)
        return a;
    while(a-b!=b)
    {
        a=a-b;
        if(a<b)
            swap(a,b);
    }
    return a-b;
}

int solve(vector<int> &vec)
{
    if(vec.size()<=0)
        return 0;
    if(vec.size()==1)
        return vec[0];
    int first=vec[0];
    for(int  i=1;i<vec.size();i++)
    {
        int num=gcb(first,vec[i]);
        if(num==1)
            return 1;
        else
            first=num;

    }
    return first;

}

int main()
{
    vector<int> vec;
    string str;
    getline(cin,str);

    istringstream istr(str);
    int num;
    while(istr>>num)
    {
        vec.push_back(num);
    }

    int data=solve(vec);
    cout<<data<<endl;

    return 0;
}

求余数的另外一种是辗转相除法。

int gcb(int a,int b)
{
    if(a<b)
        swap(a,b);
    else if(a==b)
        return a;
    while(a%b!=0)
    {
        a=a%b;
        if(a<b)
            swap(a,b);
    }
    return b;
}

求一个数组的最小公倍数

#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

//最小公倍数为2个数相乘除以最大公约数
int gcb(int a,int b)
{
    int oa=a;
    int ob=b;
    if(a<b)
        swap(a,b);
    else if(a==b)
        return a;
    while(a%b!=0)
    {
        a=a%b;
        if(a<b)
            swap(a,b);
    }
    return oa*ob/b;
}

int solve(vector<int> &vec)
{
    if(vec.size()<=0)
        return 0;
    if(vec.size()==1)
        return vec[0];
    int first=vec[0];
    for(int  i=1;i<vec.size();i++)
    {
        int num=gcb(first,vec[i]);
        if(num==1)
            return 1;
        else
            first=num;

    }
    return first;

}

int main()
{
    vector<int> vec;
    string str;
    getline(cin,str);

    istringstream istr(str);
    int num;
    while(istr>>num)
    {
        vec.push_back(num);
    }

    int data=solve(vec);
    cout<<data<<endl;

    return 0;
}

把gcb函数改下即可,改为求最小公倍数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值