c++实现最大公约数和最小公倍数简单代码
时间: 2024-01-02 07:03:20 浏览: 82
以下是使用C++标准库中的<numeric>头文件中的函数求解最大公约数和最小公倍数的示例代码:
```cpp
#include <iostream>
#include <numeric>
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;
}
```
其中,std::gcd(num1, num2)用于计算num1和num2的最大公约数,std::lcm(num1, num2)用于计算num1和num2的最小公倍数。
相关问题
c++求最大公约数和最小公倍数
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 a, b;
cin >> a >> b;
cout << "最大公约数:" << gcd(a, b) << endl;
cout << "最小公倍数:" << lcm(a, b) << endl;
return 0;
}
```
c++求最大公约数和最小公倍数
以下是C++求最大公约数和最小公倍数的代码示例:
1. 求两个数的最大公约数
```c++
int Gcd(int a, int b) {
if (b == 0) {
return a;
}
return Gcd(b, a % b);
}
```
2. 求两个数的最小公倍数
```c++
int Lcm(int a, int b) {
return a / Gcd(a, b) * b;
}
```
3. 求多个数的最大公约数
```c++
int Gcd(vector<int>& nums) {
int res = nums[0];
for (int i = 1; i < nums.size(); i++) {
res = Gcd(res, nums[i]);
}
return res;
}
```
4. 求多个数的最小公倍数
```c++
int Lcm(vector<int>& nums) {
int res = nums[0];
for (int i = 1; i < nums.size(); i++) {
res = Lcm(res, nums[i]);
}
return res;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)