问题链接:HDU1108 最小公倍数
辗转相除法;不断的让两个数做除法运算。其原理基于两个整数的最大公约数等于其中较小的数和两数的相除余数的最大公约数。
假设两数为 x,y。
先令 z = x % y ;
之后 y 赋给 x 即令 x = y ;
再将 z 赋给 y 即令 y = z;
辗转相减,其终止条件为:y 等于0时。
int gcd(int n,int m)//计算最大公约数
{
while(m!=0)
{
int t=n%m;
n=m;
m=t;
}
return n;
}
Problem Description 给定两个正整数,计算这两个数的最小公倍数。
扫描二维码关注公众号,回复:
3140666 查看本文章
Input 输入包含多组测试数据,每组只有一行,包括两个不大于1000的正整数. Output 对于每个测试用例,给出这两个数的最小公倍数,每个实例输出一行。 Sample Input 10 14 Sample Output 70 Source |
#include <iostream>
using namespace std;
////////////ac
int gcd(int n,int m)//计算最大公约数
{
while(m!=0)
{
int t=n%m;
n=m;
m=t;
}
return n;
}
int lcm(int a,int b)//计算最小公倍数
{
return a/gcd(a,b)*b;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
cout<<lcm(n,m)<<endl;
}
return 0;
}