两个数的最小公约数的c++代码
时间: 2024-05-14 19:15:00 浏览: 23
以下是两个数的最小公约数的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 << "请输入两个整数:";
cin >> a >> b;
int c = gcd(a, b);
cout << a << "和" << b << "的最小公约数为:" << c << endl;
return 0;
}
```
该代码使用递归函数来实现最大公约数的计算。在主函数中,用户输入两个整数,然后调用gcd函数计算它们的最小公约数c,最后输出结果。
相关问题
求解n个数的最大公约数c++代码
以下是求解n个数的最大公约数的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 n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int result = arr[0];
for (int i = 1; i < n; i++) {
result = gcd(result, arr[i]);
}
cout << "最大公约数为:" << result << endl;
return 0;
}
```
首先输入n,接着输入n个数到数组中,然后利用辗转相除法求解最大公约数,最后输出结果。
求n个数的最大公约数c++代码
以下是使用欧几里得算法求解n个数的最大公约数的C++代码:
```C++
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int findGCD(int arr[], int n) {
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
int main() {
int n;
cout << "Enter the number of integers: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " integers: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "The GCD of " << n << " integers is: " << findGCD(arr, n) << endl;
return 0;
}
```
在该代码中,`gcd()` 函数使用了欧几里得算法(又称辗转相除法)来计算两个数的最大公约数。`findGCD()` 函数则使用循环,来计算多个数的最大公约数。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)