Skip to content

Commit 9f191ea

Browse files
authored
Merge pull request AllAlgorithms#16 from Bharat-Reddy/master
Algorithm for finding GCD of an array of elements Added
2 parents 0b13f3e + 1230d1f commit 9f191ea

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

math/gcd_of_array.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// C++ program to find GCD of an array of integers
2+
//Author Bharat Reddy
3+
4+
#include <bits/stdc++.h>
5+
using namespace std;
6+
7+
int gcd(int a, int b)
8+
{
9+
if (a == 0)
10+
return b;
11+
return gcd(b % a, a);
12+
}
13+
14+
15+
int findGCD(int arr[], int n)
16+
{
17+
int result = arr[0];
18+
for (int i = 1; i < n; i++)
19+
result = gcd(arr[i], result);
20+
21+
return result;
22+
}
23+
24+
int main()
25+
{
26+
int n;
27+
cout<<"Enter size of array : ";
28+
cin>>n;
29+
int a[n];
30+
cout<<"Enter elements of array"<<endl;
31+
int i;
32+
for(i=0;i<n;i++)
33+
cin>>a[i];
34+
cout << findGCD(a, n) << endl;
35+
return 0;
36+
}

0 commit comments

Comments
 (0)