C++输入两个正整数m和n,求其最大公约数和最小公倍数代码
时间: 2023-11-03 13:42:01 浏览: 41
#include <stdio.h>
int main() {
int m, n, gcd, lcm, i;
scanf("%d %d", &m, &n);
gcd = 1;
lcm = m * n;
for (i = 2; i <= m && i <= n; i++) {
if (m % i == 0 && n % i == 0) {
gcd = i;
}
}
lcm /= gcd;
printf("最大公约数:%d\n", gcd);
printf("最小公倍数:%d\n", lcm);
return 0;
}
相关问题
C++输入两个正整数m和n求其最大公约数和最小公倍数
以下是C++代码实现:
```c++
#include <iostream>
using namespace std;
// 求最大公约数函数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 求最小公倍数函数
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int m, n;
cout << "请输入两个正整数m和n:" << endl;
cin >> m >> n;
// 求最大公约数
int max_common_divisor = gcd(m, n);
cout << "最大公约数为:" << max_common_divisor << endl;
// 求最小公倍数
int min_common_multiple = lcm(m, n);
cout << "最小公倍数为:" << min_common_multiple << endl;
return 0;
}
```
输入示例:
```
请输入两个正整数m和n:
36 48
```
输出示例:
```
最大公约数为:12
最小公倍数为:144
```
c++输入两个正整数m和n,求其最大公约数和最小公倍数。
以下是C++求两个正整数最大公约数和最小公倍数的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int m, n, gcd, lcm, temp;
cout << "请输入两个正整数,用空格隔开:" << endl;
cin >> m >> n;
// 求最大公约数
temp = m % n;
while (temp != 0) {
m = n;
n = temp;
temp = m % n;
}
gcd = n;
// 求最小公倍数
lcm = m * n / gcd;
cout << "最大公约数是:" << gcd << endl;
cout << "最小公倍数是:" << lcm << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)