题目:http://acm.nyist.edu.cn/JudgeOnline/status.php?pid=40
求最大公约数和最小公倍数。。。
思路:欧几里德算法求出最大公约数,即最大公约数 = gcd(a, b),然后再用(a*b)/gcd(a, b)即为最小公倍数。
然而不知道为啥用递归的方法求gcd会WA。。。so,还是用迭代实现辗转相除法吧。。。
如果不WA的话,递归代码:
#include <bits/stdc++.h>
int gcd(int a, int b)
{
return a%b ? gcd(a, a%b) : b;
}
int main()
{
int t, a, b;
scanf("%d", &t);
while (t--)
{
scanf("%d", &a);
scanf("%d", &b);
int e = gcd(a, b);
printf("%d %d
", e, a*b/e);
}
return 0;
}
AC代码:
#include <bits/stdc++.h>
int main()
{
int t, a, b, c, d;
scanf("%d", &t);
while (t--)
{
scanf("%d", &a);
scanf("%d", &b);
c = a, d = b;
while(b)
{
int tem = b;
b = a%b;
a = tem;
}
printf("%d %d
", a, c*d/a);
}
return 0;
}