c++定义函数求最小公倍数和最大公约数
时间: 2024-06-12 08:11:20 浏览: 17
C++ 标准库中的 <numeric> 头文件提供了一些用于计算最大公约数和最小公倍数的函数。<numeric> 头文件中的 gcd() 函数可以用于计算最大公约数,而 lcm() 函数可以用于计算最小公倍数。另外,还可以使用辗转相除法和辗转相减法来实现求最大公约数的功能。其中,辗转相除法的代码示例为:
int maxDivisor(int a, int b) {
int c = b;
while (a%b != 0) {
c = a%b;
a = b;
b = c;
}
return c;
}
而辗转相减法的代码示例为:
int maxDivisor(int a, int b) {
while (a != b) {
if (a > b) {
a = a - b;
} else {
b = b - a;
}
}
return a;
}
使用欧几里得算法求解最大公约数和最小公倍数的代码示例为:
#include <iostream>
// 求最大公约数
int gcd(int a, int b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
// 求最小公倍数
int lcm(int a, int b) {
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;
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)