C++求最大公约数和最小公倍数
时间: 2025-05-21 09:37:54 浏览: 23
### C++ 实现最大公约数和最小公倍数
以下是使用 **C++** 编写的一个完整的程序来计算两个整数的最大公约数(GCD)和最小公倍数(LCM),基于欧几里得算法[^1]:
```cpp
#include <iostream>
// 使用欧几里得算法求最大公约数
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// 基于 GCD 计算 LCM
int lcm(int a, int b) {
if (a == 0 || b == 0)
return 0;
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
std::cout << "输入两个整数: ";
std::cin >> num1 >> num2;
int greatestCommonDivisor = gcd(num1, num2);
int leastCommonMultiple = lcm(num1, num2);
std::cout << "最大公约数: " << greatestCommonDivisor << std::endl;
std::cout << "最小公倍数: " << leastCommonMultiple << std::endl;
return 0;
}
```
#### 解释
- `gcd` 函数实现了经典的欧几里得算法,用于找到两个整数的最大公约数[^1]。
- `lcm` 函数通过公式 \( \text{LCM}(a, b) = \frac{|a \times b|}{\text{GCD}(a, b)} \) 来计算最小公倍数。
另一种方式可以利用 `<numeric>` 中的标准库函数 `std::gcd` 和 `std::lcm`(自 C++17 起支持)[^1]:
```cpp
#include <iostream>
#include <numeric> // 提供 std::gcd 和 std::lcm
int main() {
int num1, num2;
std::cout << "输入两个整数: ";
std::cin >> num1 >> num2;
int greatestCommonDivisor = std::gcd(num1, num2);
int leastCommonMultiple = std::lcm(num1, num2);
std::cout << "最大公约数: " << greatestCommonDivisor << std::endl;
std::cout << "最小公倍数: " << leastCommonMultiple << std::endl;
return 0;
}
```
此方法更加简洁,适合现代 C++ 开发环境下的需求。
---
### 另一种暴力枚举法
如果不想采用高效的欧几里得算法,则可以通过暴力枚举的方式逐一尝试可能的因数。这种方法效率较低,但在某些特定场景下仍然适用[^3]:
```cpp
#include <iostream>
int find_gcd_brute_force(int a, int b) {
int smaller = (a < b) ? a : b;
for (int i = smaller; i >= 1; --i) {
if ((a % i == 0) && (b % i == 0))
return i;
}
return 1; // 如果无公共因子则返回 1
}
int main() {
int num1, num2;
std::cout << "输入两个整数: ";
std::cin >> num1 >> num2;
int greatestCommonDivisor = find_gcd_brute_force(num1, num2);
int leastCommonMultiple = (num1 * num2) / greatestCommonDivisor;
std::cout << "最大公约数: " << greatestCommonDivisor << std::endl;
std::cout << "最小公倍数: " << leastCommonMultiple << std::endl;
return 0;
}
```
这种实现虽然直观易懂,但对于较大的数值会显得非常低效[^3]。
---
阅读全文
相关推荐
















