1011 最大公约数GCD
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
Problem Description
输入2个正整数A,B,求A与B的最大公约数。
Input
2个数A,B,中间用空格隔开。(1<= A,B <= 10^9)
Output
输出A与B的最大公约数。
Input示例
30 105
Output示例
15
其实就是板子题, 会了模板就可以了,很简单
AC代码:
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
//模板:
int GCD(int a, int b){
if(b){
// printf("(%d, %d)", b, a%b);
return GCD(b, a%b);
} else {
return a;
}
/*也可以用这种写法,更简洁
return b ? GCD(b, a % b) : a;
*/
}
int main(){
int a, b;
while(scanf("%d %d", &a, &b) != EOF)
{
printf("%d\n", GCD(a, b));
}
return 0;
}
本题须知:
GCD(最大公约数)这里用代码实现用的是欧几里德算法(辗转相除法)
欧几里德算法(辗转相除法)
在两个数中,找出大数.用大数除以小数.得到整数商和余数.然后再不断地用除数(原来的小数)除以余数.直到没有余数为止.那么除数即为最大公约数.
例:求161与112的最大公约数.
161÷112=1……49
112÷49=2……14
49÷14=3……7
14÷7=2
所以161和112的最大公约数是 7
那我们这个样例来说:
次数 a b a%b
1 30 105 30
2 105 30 15
3 30 15 0
所以你不需要区分是a<b, 还是 b<a;因为在取余操作中已经将a,b s 的顺序转化为a<b,才去运算的
这里提前说一下LCM(最小公倍数),它的求解是基于GCD上的
LCM(a, b) = ( a / GCD(a,b)) * (b / GCD(a,b)) * GCD(a,b)= a * b / GCD(a, b);