Find Greatest Common Divisor of Array

 Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.


The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.


 


Example 1:


Input: nums = [2,5,6,9,10]

Output: 2

Explanation:

The smallest number in nums is 2.

The largest number in nums is 10.

The greatest common divisor of 2 and 10 is 2.

Example 2:


Input: nums = [7,5,6,8,3]

Output: 1

Explanation:

The smallest number in nums is 3.

The largest number in nums is 8.

The greatest common divisor of 3 and 8 is 1.

Example 3:


Input: nums = [3,3]

Output: 3

Explanation:

The smallest number in nums is 3.

The largest number in nums is 3.

The greatest common divisor of 3 and 3 is 3.



✅ Approaches to Find GCD


🥇 1. Euclidean Algorithm (Efficient & Most Used)

👉 Logic:

  • Keep replacing (a, b) with (b, a % b) until b = 0

  • When b = 0, a is the GCD.

✏️ Example:

Find GCD of 48 and 18

gcd(48, 18)

→ gcd(18, 48 % 18) = gcd(18, 12)

→ gcd(12, 18 % 12) = gcd(12, 6)

→ gcd(6, 12 % 6) = gcd(6, 0)

→ GCD = 6

✅ Code (Java):
public int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

🥈 2. Recursive Euclidean Algorithm

✅ Code (Java):

public int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

🧠 Time Complexity:

  • O(log(min(a, b)))

  • Very fast even for large numbers.


✅ Key Fact:

In each step, the value of b becomes smaller. And it gets reduced quickly.

In fact, the Euclidean Algorithm takes at most log(min(a, b)) steps.

Because in the worst case, the size of numbers reduces approximately by half in every step. So it's logarithmic time.


class Solution {
   
    public static int gcd(int a,int b)
    {
        if(b==0)return a;
        return gcd(b,a%b);
    }
    public int findGCD(int[] nums) {
       
        int min=Arrays.stream(nums).min().getAsInt();
        int max=Arrays.stream(nums).max().getAsInt();

        return gcd(max,min);
    }
}

✅ Summary:

MethodTime ComplexityEfficientNotes
EuclideanO(log(min(a,b)))✅ BestUsed in most applications
RecursiveO(log(min(a,b)))✅ BestSame logic, using recursion
Brute ForceO(min(a,b))❌ SlowOnly for small numbers


Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence