FIND GCD OF AN ARRAY

Given an array of N positive integers. Your task is to find the GCD of all numbers of the array.
Input:
First line of input contains number of test cases T. First line of test case contains a positive integer N, size of the array. Next line contains the array elements.
Output:
For each testcase, print the GCD of array elements.
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= Arr[i] <= 106
Example:
Input:
1
2
5 10
Output:
5


import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int i=0;i<t;i++)
{
  int x=s.nextInt();
  int[] arr=new int[x];
  for(int j=0;j<x;j++)
  {
      arr[j]=s.nextInt();
  }
  System.out.println(findGCD(arr, x)); 
}
}
static int findGCD(int arr[], int x) 
    { 
        int result = arr[0]; 
        for (int i = 1; i < x; i++) 
            result = gcd(arr[i], result); 
  
        return result; 
    } 
    static int gcd(int a, int b) 
    { 
        if (a == 0) 
            return b; 
        return gcd(b % a, a); 
    } 
}

Comments

Popular posts from this blog

Problem Statement Of Real Estate Use Cases

Problem Statement Of Bank Marketing analysis

Hadoop