forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindGreatestCommonDivisorOfArray.java
More file actions
61 lines (45 loc) · 1.43 KB
/
FindGreatestCommonDivisorOfArray.java
File metadata and controls
61 lines (45 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
LEETCODE QUESTION : 1979. 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.
*/
//The code
class FindGreatestCommonDivisorOfArray {
public int findGCD(int[] nums) {
insertion(nums);
int large = nums[nums.length - 1];
int small = nums[0];
int rem = large % small;
if (rem == 0) {
return small;
} else
return gcd(small, large);
}
static int gcd(int a, int b) {
int result = Math.min(a, b); // Find Minimum of a and b
while (result > 0) {
if (a % result == 0 && b % result == 0) {
break;
}
result--;
}
return result; // return gcd of a and b
}
private void insertion(int arr[]) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
// swap
swaparray(arr, j, j - 1);
} else {
break;
}
}
}
}
static void swaparray(int[] arr, int first, int second) {
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}