如何用一个例子编写C语言程序来查找两个数的最小公倍数?根据数学,两个或多个整数的最小公倍数是能被给定整数值整除且没有余数的最小正整数。
例如,整数2和3的最小公倍数是12,因为12是能被2和3整除的最小正整数(余数为0)。
使用While循环的C语言程序来查找两个数的最小公倍数
此程序允许用户输入两个正整数值,我们将使用While循环来查找或计算这两个数的最小公倍数。请记住,有些人会称最小公倍数为LCM。
#include <stdio.h>
int main()
{
int Num1, Num2, max_Value;
printf("Please Enter two integer Values \n");
scanf("%d %d", &Num1, &Num2);
max_Value = (Num1 > Num2)? Num1 : Num2;
while(1) //Alway True
{
if(max_Value % Num1 == 0 && max_Value % Num2 == 0)
{
printf("LCM of %d and %d = %d", Num1, Num2, max_Value);
break;
}
++max_Value;
}
return 0;
}

使用GCD的C语言程序来查找两个数的最小公倍数
在这个LCM程序中,我们将使用While循环来计算这两个值的最小公倍数。
提示:最小公倍数的基本公式是LCM(a, b) = (a * b) / GCD。我们已经在之前的文章中解释了GCD。请参考本编程系列中的查找两个数的GCD的C语言程序文章以获取更多信息。
#include <stdio.h>
int main()
{
int Num1, Num2, LCM, Temp, GCD;
printf("Please Enter two integer Values \n");
scanf("%d %d", &Num1, &Num2);
int a = Num1;
int b = Num2;
while (Num2 != 0) {
Temp = Num2;
Num2 = Num1 % Num2;
Num1 = Temp;
}
GCD = Num1;
printf("GCD of %d and %d = %d \n", a, b, GCD);
LCM = (a * b) / GCD;
printf("LCM of %d and %d = %d", a, b, LCM);
return 0;
}

使用递归的C语言程序来查找两个数的最小公倍数
这个程序允许您输入两个正整数值。接下来,我们将通过递归调用函数来计算这两个值的最小公倍数。请参考C语言递归以供进一步参考。
#include <stdio.h>
long gcd(long x, long y);
int main()
{
int Num1, Num2, GD, res;
printf("Please Enter two integer Values \n");
scanf("%d %d", &Num1, &Num2);
GD = gcd(Num1, Num2);
res = (Num1 * Num2) / GD;
printf("LCM of %d and %d is = %d", Num1, Num2, res);
return 0;
}
long gcd(long x, long y)
{
if (y == 0) {
return x;
}
else {
return gcd(y, x % y);
}
}

以下语句将使用传统公式查找最小公倍数。
res = (Num1 * Num2) / GCD;
当编译器在main()程序示例中遇到long gcd(long x, long y)行时,编译器将立即跳转到下面的函数
long gcd(long x, long y)
在上述指定的函数中,return gcd(y, x % y)语句将帮助程序使用更新后的值递归调用函数。如果您在两个数的最小公倍数示例中遗漏了此语句,那么在完成第一行后,程序将终止。
让我们看一下If条件if (y == 0),它将检查数字是否等于0。对于递归函数,在使用函数递归调用之前放置一个条件非常重要。否则,我们将陷入无限执行(类似于无限循环)。请注意:)