作业帮 > 数学 > 作业

求两个数的最大公约数和最小公倍数用c++

来源:学生作业帮 编辑:作业帮 分类:数学作业 时间:2024/05/14 19:50:00
求两个数的最大公约数和最小公倍数用c++
是辗转法
代码:
long gcd(long x,long y)//最大公约数
{ // get the greatest common divisor of two integer(GCD)
long t;
if (x==0||y==0)
return 0;
if (x < 0)
x = -x;
if (y < 0)
y = -y;
if (x < y)
{
t = x;
x = y;
y = t;
}
while((t = x%y)!=0)
{
x = y;
y = t;
}
return y;
}
inline long lcm(long x,long y)//最小共倍数
{ // get the least common multiple of two integer(LCM)
return (x / gcd(x,y) * y);
}