AcWing 872:最大公约数 ← 递归及非递归解法等

【题目来源】
https://www.acwing.com/problem/content/874/

【题目描述】
给定 n 对正整数 ai,bi,请你求出每对数的最大公约数。

【输入格式】
第一行包含整数 n。
接下来 n 行,每行包含一个整数对 ai,bi。

【输出格式】
输出共 n 行,每行输出一个整数对的最大公约数。

【数据范围】
1≤n≤10^5,
1≤ai,bi≤2×10^9

【输入样例】
2
3 6
4 6

【输出样例】
3
2

【算法代码:
辗转相除法 ← 递归】

#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 n;
    cin>>n;
    while(n--) {
        int a,b;
        cin>>a>>b;
        cout<<gcd(a,b)<<endl;
    }

    return 0;
}


/*
in:
2
3 6
4 6

out:
3
2
*/

【算法代码:更相减损法 ← 非递归】

#include <bits/stdc++.h>
using namespace std;

int gcd(int a,int b) {
    while(a!=b) {
        if(a>b) a-=b;
        else b-=a;
    }
    return a;
}

int main() {
    int n;
    cin>>n;
    while(n--) {
        int a,b;
        cin>>a>>b;
        cout<<gcd(a,b)<<endl;
    }

    return 0;
}


/*
in:
2
3 6
4 6

out:
3
2
*/

【算法代码:利用 algorithm 包中自带的函数 __gcd()

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin>>n;
    while(n--) {
        int a,b;
        cin>>a>>b;
        cout<<__gcd(a,b)<<endl;
    }

    return 0;
}


/*
in:
2
3 6
4 6

out:
3
2
*/

【算法代码:依据数学定义自编 gcd() 函数】
本代码中,依据数学定义自编 gcd() 函数。但由于本题数据规模太大,显然会超时(
TLE)。

#include <bits/stdc++.h>
using namespace std;

int gcd(int a,int b) {
    for(int i=min(a,b); i>=2; i--) {
        if(a%i==0 && b%i==0) return i;
    }
}

int main() {
    int n;
    cin>>n;
    while(n--) {
        int a,b;
        cin>>a>>b;
        cout<<gcd(a,b)<<endl;
    }

    return 0;
}


/*
in:
2
3 6
4 6

out:
3
2
*/





【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/110733164
https://www.acwing.com/solution/content/98177/



 

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值