# How to calculate greatest common divisor of two or more numbers/arrays in JavaScript ?

• Last Updated : 22 Apr, 2021

Given two or more numbers/array of numbers and the task is to find the GCD of the given numbers/array elements in JavaScript.

Examples:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

```Input  : arr[] = {1, 2, 3}
Output : 1

Input  : arr[] = {2, 4, 6, 8}
Output : 2```

The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCD of pairs of numbers.

```gcd(a, b, c) = gcd(a, gcd(b, c))
= gcd(gcd(a, b), c)
= gcd(gcd(a, c), b)```

For an array of elements, we do the following. We will also check for the result if the result at any step becomes 1 we will just return 1 as gcd(1, x) = 1.

```result = arr
For i = 1 to n-1
result = GCD(result, arr[i])```

Below is the implementation of the above approach.

Code Example:

## Javascript

 ` `

Output:

`2`

Time Complexity: O(N * log(M)), where M is the smallest element of the array and N is the length of the array.

My Personal Notes arrow_drop_up
Recommended Articles
Page :