求三个数的最大公约c++
时间: 2023-08-29 10:07:27 浏览: 140
以下是用C++实现求三个数的最大公约数的代码:
```c++
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int gcd(int a, int b, int c) {
return gcd(gcd(a, b), c);
}
int main() {
int a, b, c;
cout << "请输入三个数:";
cin >> a >> b >> c;
int result = gcd(a, b, c);
cout << "它们的最大公约数为:" << result << endl;
return 0;
}
```
首先定义了一个求两个数最大公约数的函数`gcd`,然后通过递归调用求出三个数的最大公约数。最后在主程序中输入三个数,调用`gcd`函数并输出结果。
相关问题
求两个数的最大公约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 c = gcd(a, b);
cout << "The GCD of " << a << " and " << b << " is " << c << endl;
return 0;
}
```
输入两个数后,程序会输出它们的最大公约数。
java求三个数的最大公约递归
以下是 Java 代码,用于求三个数的最大公约数,采用递归方式实现:
```java
public class Main {
public static void main(String[] args) {
int a = 12, b = 18, c = 24;
int result = gcd(gcd(a, b), c);
System.out.println("最大公约数为:" + result);
}
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
}
```
这个程序的输出结果是:
```
最大公约数为:6
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)