最大公约数 四种求法

最大公约数

总时间限制: 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值