Monday, September 11, 2017

GCD of N Integers

N integers are passed as input to the program. The program must print the GCD (HCF) of these N integers.

Input Format:
The first line contains N. The second line contains N integers each separated by a space.

Output Format:
The first line contains the HCF of these N numbers.

Boundary Conditions:
2 <= N <= 100

Example Input/Output 1:
Input:
4
15 20 30 50
Output:
5

Solution:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
 int n,t;
 cin>>n;
 int a[n];
 for(int i=0;i<n;i++)
  cin>>a[i];
 for(int i=0;i<n-1;i++)
  {
      while(a[i+1]!=0)
       {
          t=a[i+1];
          a[i+1]=a[i]%a[i+1];
          a[i]=t;
       }
       a[i+1]=a[i];
  }
  cout<<a[n-1];
}
Share: