TheAlgorithms-C-Plus-Plus/GCD_of_n_numbers.cpp

24 lines
594 B
C++
Raw Normal View History

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