In this post we will discuss **hot to find GCD of n numbers** i.e an Array in Java.

**Example:**

1 2 3 4 5 | Input: [16, 8, 24] Output: 8 Input: [16, 8, 24, 4] Output: 4 |

**Greatest Common Divisor** (GCD) of two or more positive numbers is the largest of them which divides all of them. For example, gcd of [16, 8, 24] is 8.

The trick to calculate the GCD of multiple numbers is to use the gcd of two numbers with the third one.

For example, first, we will calculate the GCD of the first two numbers of the array (say x), then we will calculate the gcd of the x and the third number (say y) then again we will compute gcd of y and the fourth number.

This process will repeat until the last number. The final GCD which we get will be the answer.

To implement the same we will have to loop through the array. Let’s do it.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class Main { public static void main(String[] args) { int array[] = {16, 8, 24, 4}; int result = array[0]; //Loop through the array and find GCD //by combining the GCD of previous numbers for(int i=1; i<array.length; i++){ result = findGCD(array[i], result); } System.out.print("GCD: "+result); } //function to find GCD of two numbers public static int findGCD(int a, int b){ if(b == 0) return a; return findGCD(b, a%b); } } |

**Output**

1 | 8 |

If you have any suggestions or doubts then comment below.