两个数的最小公倍数
我的 LCM 程序得到错误的结果。
我首先找到数字的最大公约数,然后将乘积除以最大公约数。
int gcd(int x, int y)
{
while(y != 0)
{
int save = y;
y = x % y;
x = save;
}
return y;
}
int lcm(int x, int y)
{
int prod = x * y;
int Gcd = gcd(x,y);
int lcm = prod / Gcd;
return lcm;
}
非常感谢任何帮助。
I am getting wrong result for my LCM program.
Ifirst find gcd of the numbers and then divide the product with gcd.
int gcd(int x, int y)
{
while(y != 0)
{
int save = y;
y = x % y;
x = save;
}
return y;
}
int lcm(int x, int y)
{
int prod = x * y;
int Gcd = gcd(x,y);
int lcm = prod / Gcd;
return lcm;
}
Any help much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的
gcd
函数将始终返回0
。更改为
理解欧几里得算法:
考虑
x = 12
和y = 18
正如您所看到的,当
y
变为零时x 将是
gcd
,因此您需要返回x
而不是y
。另外,在计算 lcm 时,您首先将数字相乘,这可能会导致溢出。相反,你可以这样做:
但如果
lcm
无法放入int
中,则必须将其设为long long
Your
gcd
function will always return0
. Changeto
Understand the Euclid's algorithm:
consider
x = 12
andy = 18
As you can see when
y
becomes zerox
will be thegcd
so you need to returnx
and noty
.Also while calculating lcm you are multiplying the numbers first which can cause overflow. Instead you can do:
but if
lcm
cannot fit in anint
you'll have to make itlong long
问题1)
int gcd = gcd(x,y);
gcd
已经被定义为一个函数。不能定义同名的变量。问题2)将
gcd()
中的return y
改为return x
,否则每次都会返回0。问题3)如果
x
和y
很大,x * y
可能会溢出。Problem 1)
int gcd = gcd(x,y);
gcd
is already defined to be a function. You cannot define a variable with the same name.Problem 2) Change
return y
toreturn x
ingcd()
otherwise 0 will be returned everytime.Problem 3)
x * y
may overflow ifx
andy
are large.您应该在 gcd 函数中返回 x 而不是 y。
另外,您确定产品 x*y 始终适合
int
吗?使用long long
也可能是个好主意。You should return x instead of y in your gcd function.
Also, are you sure the product x*y will always fit into an
int
? Might be a good idea to use along long
for that as well.这个 C 程序是寻找 LCM 的不同方法
This C program is different approach towards finding LCM