最大公约数
总时间限制: 1000ms 内存限制: 65536kB
描述
给定两个正整数,求它们的最大公约数。
输入
有多组数据,每行为两个正整数,且不超过int可以表示的范围。
输出
每行对应输出最大公约数。
样例输入
4 8
8 6
200 300
样例输出
4
2
100
提示
系统的测试文件中数据有很多组,因此同学们在程序里要写循环读取数据并判断是否读完文件的代码。
如果不知道如何处理,可以参考下面的两个模板:
C++这样写:
while(cin>>x>>y)
{
求x和y最大公约数的代码
}
C这样写:
while(scanf(%x %y",&x,&y)!=EOF)
{
求x和y最大公约数的代码
}
AC代码
#include<bits/stdc++.h> //枚举法求最小公约数
using namespace std;
int main(){
int a,b,ans=0;
while(cin>>a>>b){
for(int i=1;i<=min(a,b);i++){
if(a%i==0&&b%i==0){
ans=i;}
}
cout<<ans<<endl;
}
return 0;
}
#include<bits/stdc++.h> //分解质因子法求最小公约数
using namespace std;
int a,b,ans=1;
void gcd(int a,int b){
for(int x=2;x*x<=min(a,b);x++){
while(a%x==0&&b%x==0){
a/=x; b/=x; ans*=x;
}
while(a%x==0) a/=x;
while(b%x==0) b/=x;
}
if(a%b==0) ans*=b;
else if(b%a==0) ans*=a;
cout<<ans<<endl;
}
int main(){
while(cin>>a>>b){
gcd(a,b);
ans=1;
}
return 0;
}
#include<bits/stdc++.h> //辗转相除法求最小公约数
using namespace std;
int gcd(int a,int b){
if(b==0) return a;
else return gcd(b,a%b);
}
int main(){
int a,b;
while(cin>>a>>b){
cout<<gcd(a,b)<<endl;
}
return 0;
}
#include<bits/stdc++.h> //二进制法求最小公约数
using namespace std;
int gcd(int a,int b){
if(a==b) return a;
if(a<b) return gcd(b,a);
if(a&1==0) return (b&1==0)?2*gcd(a/2,b/2):gcd(a/2,b);
return (b&1==0)?gcd(a,b/2):gcd(b,a-b);
}
int main(){
int a,b;
while(cin>>a>>b){
cout<<gcd(a,b)<<endl;
}
return 0;
}