publicclassSolution {
publicintfindGCD(int[] nums) {
int ans = nums[0];
for (int i = 1; i < nums.length; i++) {
ans = gcd(ans, nums[i]);
if (ans == 1) {
break; // GCD can't be smaller than 1 }
}
return ans;
}
privateintgcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] nums1 = {12, 15, 21};
System.out.println(solution.findGCD(nums1)); // Output: 3int[] nums2 = {24, 36, 48};
System.out.println(solution.findGCD(nums2)); // Output: 12 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
deffindGCD(self, nums: List[int]) -> int:
defgcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a
ans = nums[0]
for num in nums[1:]:
ans = gcd(ans, num)
if ans ==1:
break# GCD can't be smaller than 1return ans
# Example usagesol = Solution()
print(sol.findGCD([12, 15, 21])) # Output: 3print(sol.findGCD([24, 36, 48])) # Output: 12