最小公倍数c++和最大公约数
时间: 2024-06-13 14:06:18 浏览: 87
求两个数的最小公倍数和最大公约数C++
5星 · 资源好评率100%
以下是C++中求最小公倍数和最大公约数的例子:
1. 最大公约数
```c++
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a = 12, b = 18;
cout << "The GCD of " << a << " and " << b << " is " << gcd(a, b) << endl; // 输出:The GCD of 12 and 18 is 6
return 0;
}
```
2. 最小公倍数
```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 a = 12, b = 18;
cout << "The LCM of " << a << " and " << b << " is " << lcm(a, b) << endl; // 输出:The LCM of 12 and 18 is 36
return 0;
}
```
阅读全文