1014: 最小公倍数
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 8348 Solved: 1872
[Submit][Status][Web Board]
Description
求两个数的最小公倍数LCM(Least Common Multiple)
Input
每行包含两个数a,b
当a和b都等于0时表示输入结束,这组数据不用输出
Output
每行包含一个正整数:a和b的最小公倍数
Sample Input
4 6 3 5 0 0
Sample Output
12 15
#include<stdio.h>
int gcd(int a,int b);
int main()
{
int a,b;
int lcm;
while(~scanf("%d %d",&a,&b))
{
if(a==0&&b==0)break;
lcm=a/gcd(a,b)*b;
printf("%d\n",lcm);
}
return 0;
}
int gcd(int a,int b)
{
if(b!=0)
return gcd(b,a%b);
else
return a;
}
主要问题是 lcm=a/gcd(a,b)*b 这一步,必须要先除后乘,不能先a*b后除以gcd。因为a*b可能会超出 int 类型的上限。