练习题007:求两个数的最大公因数和最小公倍数
程序员文章站
2022-05-11 20:25:00
...
最大公约数:辗转相除法;
最小公倍数=两数之积 / 两者的最大公约数。
#include <stdio.h>
#include <windows.h>
int main()
{
unsigned long number1 = 0; //两个整数
unsigned long number2 = 0;
unsigned long tem = 0;
unsigned long gcd = 0; //最大公约数
unsigned long lcm = 0; //最小公倍数
while (1)
{
printf("Please input two numbers: ");
scanf("%lu%lu", &number1, &number2);
if (number1 <= 0 || number2 <= 0)
{
printf("input error!\n");
continue;
}
else
{
break;
}
}
unsigned long r1 = number1; //保留两个整数的初始值,方便以后计算最大公倍数
unsigned long r2 = number2;
while (number1 % number2 != 0)
{
tem = number1 % number2;
number1 = number2;
number2 = tem;
}
gcd = number2;
lcm = (r1 * r2) / gcd;
printf("Their Greatest Common Divisor is %lu.\n", gcd);
printf("Their Least Common Multiple is %lu.\n", lcm);
system("pause");
return 0;
}
运行结果: