写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数,并输出结果 c语言
时间: 2024-12-17 16:40:08 浏览: 55
在C语言中,我们可以利用辗转相除法(欧几里得算法)来计算两个整数的最大公约数(GCD),然后通过最大公约数和两个数的关系来计算最小公倍数(LCM)。以下是相关的代码示例:
```c
#include <stdio.h>
// Function to calculate GCD using Euclidean algorithm
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
// Function to calculate LCM
int lcm(int a, int b) {
int temp = gcd(a, b);
return (a * b) / temp; // LCM = |a*b| / GCD(a, b)
}
// Main function to call the above functions and display results
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
int result_gcd = gcd(num1, num2);
int result_lcm = lcm(num1, num2);
printf("The Greatest Common Divisor (GCD) of %d and %d is: %d\n", num1, num2, result_gcd);
printf("The Least Common Multiple (LCM) of %d and %d is: %d\n", num1, num2, result_lcm);
return 0;
}
```
在这个程序中,用户会被提示输入两个整数,然后`gcd`函数计算它们的最大公约数,`lcm`函数则基于这个GCD来计算最小公倍数。最后,主函数会打印出这两个值。
阅读全文
相关推荐

















