求一个数组的最大公约数
可以先选择前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函数改下即可,改为求最小公倍数。