- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathFindGreatestCommonDivisorOfArray.java
61 lines (45 loc) · 1.43 KB
/
FindGreatestCommonDivisorOfArray.java
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
classFindGreatestCommonDivisorOfArray {
publicintfindGCD(int[] nums) {
insertion(nums);
intlarge = nums[nums.length - 1];
intsmall = nums[0];
intrem = large % small;
if (rem == 0) {
returnsmall;
} else
returngcd(small, large);
}
staticintgcd(inta, intb) {
intresult = Math.min(a, b); // Find Minimum of a and b
while (result > 0) {
if (a % result == 0 && b % result == 0) {
break;
}
result--;
}
returnresult; // return gcd of a and b
}
privatevoidinsertion(intarr[]) {
for (inti = 0; i < arr.length - 1; i++) {
for (intj = i + 1; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
// swap
swaparray(arr, j, j - 1);
} else {
break;
}
}
}
}
staticvoidswaparray(int[] arr, intfirst, intsecond) {
inttemp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}