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)
untilb = 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
🥈 2. Recursive Euclidean Algorithm
✅ Code (Java):
🧠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.
✅ Summary:
Method | Time Complexity | Efficient | Notes |
---|---|---|---|
Euclidean | O(log(min(a,b))) | ✅ Best | Used in most applications |
Recursive | O(log(min(a,b))) | ✅ Best | Same logic, using recursion |
Brute Force | O(min(a,b)) | ❌ Slow | Only for small numbers |
Comments
Post a Comment