top of page
Click here to go to the home page of AskTheCode.

Find GCD Of N Numbers in Java | AskTheCode

Team ATC

Java program to find GCD of numbers of an Array | GCD Of N Numbers in Java | AskTheCode

 

Problem:

You have completed your recent assignment, and now you are assigned to a new. Your superior knows that you can do computations very easily so told you to find the Greatest Common Divisor.

You are given N numbers. And you have to find the GCD of N numbers.

 

Input:

  • The first line contains an integer T, the number of test cases. Then the test cases follow.

  • The only line of each test case contains N space separated integers.

 

Output:

For each testcase, output in a single line the answer to the problem.

 

Input Sample:

4
12 225 123 652 202 111 14
1 2 3 4 5 6 7 8 9 10
13 26 390 52
20
 

Output Sample:

1
1
13
20
 

Code:

import java.io.*;

public class GCD_Of_N_Num{
	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try{
			int t = Integer.parseInt(br.readLine());
			while(t-- > 0){
				String[] input = br.readLine().split(" ");
				int size = input.length;
				int[] array = new int[size];
				for (int i=0; i<size; i++)
					array[i] = Integer.parseInt(input[i]);

				System.out.println(gcd_Array(array, size));
			}
		}catch(Exception e){}
	}
	private static int gcd_A_and_B(int a, int b){
		return a % b == 0 ? b : gcd_A_and_B(b, a%b);
	}
	private static int gcd_Array(int[] array, int size){
		if (size == 1) {
			return array[0];
		}
		int temp = array[0];
		for (int i=1; i<size; i++){
			temp = gcd_A_and_B(array[i], temp);
		}
		return temp;
	}
}

Recent Posts

See All

Comments


bottom of page