两个数的最大公约数c++
时间: 2024-06-13 14:05:29 浏览: 11
两个数的最大公约数可以使用辗转相除法或者枚举法来实现。以下是两种方法的C++代码实现:
辗转相除法:
```
#include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int a = n, b = m;
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
cout << "最大公约数为:" << a << endl;
return 0;
}
```
枚举法:
```
#include <iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int x = n < m ? n : m;
for (x; x >= 1; x--) {
if (n % x == 0 && m % x == 0) {
break;
}
}
cout << "最大公约数为:" << x << endl;
return 0;
}
```
相关问题
求两个数的最大公约数c++
方法一:可以想到两个数的最大公约数可能是两个数的min,最小可能是1。所以,可以设最大公约数从min开始进行判断,如果gcd大于1并且不能同时整除m和n,那么就gcd-1,重复判断是否整除。
方法二:欧几里德算法,对于任意两个自然数m和n,用m,n,r分别表示被除数,除数,余数,m和n的最大公约数等于n和r的最大公约数,以下是辗转相除法 求m除以n的余数r当r!=0时,执行第3步;若r==0,则n为最大公约数,算法结束将n的值赋值给m,r的值赋值给n,再求m除以n的余数r转到第2步。
以上是两种求两个数的最大公约数的方法。希望能对您有所帮助。
输出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);
}
// 求n个数的最大公约数
int gcd_n(int arr[], int n) {
int res = arr[0];
for (int i = 1; i < n; i++) {
res = gcd(res, arr[i]);
}
return res;
}
int main() {
int n;
cout << "请输入数字个数n:";
cin >> n;
int arr[n];
cout << "请输入" << n << "个数字:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int res = gcd_n(arr, n);
cout << "这" << n << "个数字的最大公约数为:" << res << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-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)