c++求两个数最大公约数和最小公倍数 只能用分支和循环结构
时间: 2024-10-20 11:13:48 浏览: 30
c代码-输入两个正整数m和n,求其最大公约数和最小公倍数。
在C++中,仅使用分支和循环结构来求两个数的最大公约数(GCD,Greatest Common Divisor)和最小公倍数(LCM,Least Common Multiple)通常会涉及欧几里得算法,这是最基础并且效率高的方法。这里是一个简单的示例:
**计算最大公约数(GCD):**
```cpp
#include <iostream>
// 辗转相除法(Euclidean Algorithm)
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int result = gcd(num1, num2);
std::cout << "The GCD of " << num1 << " and " << num2 << " is " << result << "\n";
return 0;
}
```
**计算最小公倍数(LCM):**
由于LCM可以通过 GCD 和两个数直接乘积得到(即 LCM(a, b) = |a * b| / GCD(a, b)),所以也可以通过循环结构实现:
```cpp
int lcm(int a, int b) {
return abs(a * b) / gcd(a, b);
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int lcm_value = lcm(num1, num2);
std::cout << "The LCM of " << num1 << " and " << num2 << " is " << lcm_value << "\n";
return 0;
}
```
阅读全文