Leetcode 1979. Find Greatest Common Divisor of Array
Given an integer array nums
, return the greatest common divisor (GCD) of the smallest number and the largest number in the array.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
nums
?
nums
?
nums
can range from 1 to 1000.#include <iostream>
#include <vector>
#include <algorithm> // for std::min_element and std::max_element
// Function to compute the GCD using the Euclidean algorithm
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int findGCD(const std::vector<int>& nums) {
if (nums.empty()) return 0;
// Find the smallest and largest elements in the array
int min_elem = *std::min_element(nums.begin(), nums.end());
int max_elem = *std::max_element(nums.begin(), nums.end());
// Return the GCD of smallest and largest elements
return gcd(min_elem, max_elem);
}
// Example usage
int main() {
std::vector<int> nums = {2, 5, 6, 9, 10};
std::cout << "GCD of smallest and largest elements: " << findGCD(nums) << std::endl;
return 0;
}
This efficient solution guarantees that we can handle the maximum constraints comfortably.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?