求最大公约数C++代码
时间: 2023-11-14 18:14:52 浏览: 45
以下是求最大公约数的 Python 代码:
```
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
```
其中,`a` 和 `b` 分别为两个数,如果 `b` 等于 0,那么 `a` 就是最大公约数;否则,递归调用 `gcd(b, a % b)`,直到 `b` 等于 0。
相关问题
欧几里得算法求最大公约数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 main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
int result = gcd(a, b);
cout << "GCD of " << a << " and " << b << " is " << result << endl;
return 0;
}
```
在代码中,我们定义了一个函数 `gcd` 来计算最大公约数。使用欧几里得算法,我们首先判断 `b` 是否为 0,如果是,则返回 `a`。否则,我们将 `b` 和 `a % b` 作为参数递归调用 `gcd` 函数。
在 `main` 函数中,我们从用户输入中读取两个整数,然后使用 `gcd` 函数计算它们的最大公约数,并将结果打印到屏幕上。
求最大公约数的代码C++
当然,下面是一个用C++编写的求最大公约数的代码示例:
```cpp
#include <iostream>
// 函数声明
int gcd(int a, int b);
int main() {
int num1, num2;
std::cout << "请输入两个整数:" << std::endl;
std::cin >> num1 >> num2;
int result = gcd(num1, num2);
std::cout << "最大公约数是:" << result << std::endl;
return 0;
}
// 函数定义
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
```
这段代码中,我们使用了递归的方式来求解最大公约数。函数`gcd`接受两个整数参数`a`和`b`,如果`b`为0,则返回`a`作为最大公约数;否则,递归调用`gcd`函数,将`b`和`a`除以`b`的余数作为新的参数传入,直到找到最大公约数为止。
相关推荐
![](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)
![](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)