出求M,N的最大公约数和最小公倍数C语言
时间: 2023-10-10 13:15:45 浏览: 173
可以使用辗转相除法来求解最大公约数(GCD),通过以下代码实现:
```c
int gcd(int m, int n) {
int r;
while (n != 0) {
r = m % n;
m = n;
n = r;
}
return m;
}
```
而最小公倍数(LCM)可以通过以下公式来计算:
LCM = m * n / GCD(m, n)
因此,可以使用以下代码实现:
```c
int lcm(int m, int n) {
int gcd_val = gcd(m, n);
return m * n / gcd_val;
}
```
需要注意的是,如果输入的m和n为0,则它们的最大公约数和最小公倍数均为0。
相关问题
输入m,n求最大公约数和最小公倍数c语言
以下是求最大公约数和最小公倍数的C语言代码:
```c
#include <stdio.h>
int main()
{
int m, n, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &m, &n);
// 求最大公约数
for(i=1; i<=m && i<=n; ++i)
{
if(m%i==0 && n%i==0)
gcd = i;
}
// 求最小公倍数
lcm = m*n/gcd;
printf("Greatest common divisor of %d and %d is %d\n", m, n, gcd);
printf("Least common multiple of %d and %d is %d\n", m, n, lcm);
return 0;
}
```
运行结果:
```
Enter two positive integers: 12 30
Greatest common divisor of 12 and 30 is 6
Least common multiple of 12 and 30 is 60
```
C语言代码写一下求m的最大公约数和最小公倍数
以下是使用辗转相除法求两个数的最大公约数和最小公倍数的C语言代码:
```c
#include <stdio.h>
int gcd(int a, int b) { // 求最大公约数
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
int lcm(int a, int b) { // 求最小公倍数
return a / gcd(a, b) * b;
}
int main() {
int m, n;
printf("请输入两个正整数:");
scanf("%d %d", &m, &n);
printf("%d 和 %d 的最大公约数是:%d\n", m, n, gcd(m, n));
printf("%d 和 %d 的最小公倍数是:%d\n", m, n, lcm(m, n));
return 0;
}
```
运行结果:
```
请输入两个正整数:12 18
12 和 18 的最大公约数是:6
12 和 18 的最小公倍数是:36
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)