TheAlgorithms-C-Plus-Plus/GCD_of_n_numbers.cpp

24 lines
594 B
C++
Raw Normal View History

2017-06-02 11:43:26 +05:30
//This program aims at calculating the GCD of n numbers by division method
2017-06-02 11:18:56 +05:30
#include <iostream>
using namepsace std;
int main()
{
2017-06-02 11:23:54 +05:30
cout <<"Enter value of n:"<<endl;
2017-06-02 11:18:56 +05:30
cin >> n;
int a[n];
int i,j,gcd;
2017-06-02 11:43:26 +05:30
cout << "Enter the n numbers:" << endl;
2017-06-02 11:18:56 +05:30
for(i=0;i<n;i++)
cin >> a[i];
2017-06-02 11:43:26 +05:30
j=1; //to access all elements of the array starting from 1
2017-06-02 11:18:56 +05:30
gcd=a[0];
while(j<n)
{
2017-06-02 11:43:26 +05:30
if(a[j]%gcd==0) //value of gcd is as needed so far
j++; //so we check for next element
2017-06-02 11:18:56 +05:30
else
2017-06-02 11:43:26 +05:30
gcd=a[j]%gcd; //calculating GCD by division method
2017-06-02 11:18:56 +05:30
}
cout << "GCD of entered n numbers:" << gcd;
}