-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCD of array.java
More file actions
54 lines (42 loc) · 1.04 KB
/
GCD of array.java
File metadata and controls
54 lines (42 loc) · 1.04 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
class Solution {
public int findGCD(int[] nums) {
int max = 0;
int min = 1001;
// Find the min and max from array
for(int e : nums){
max = Math.max(max,e);
min = Math.min(min,e);
}
return gcd(min, max);
}
private int gcd(int a, int b) {
while(b != 0) {
if(a > b) a = a - b;
else b = b - a;
}
return a;
}
}
//another approach
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
// your code here
Scanner s = new Scanner(System.in);
int a = s.nextInt();
int b = s.nextInt();
System.out.println(gcd(a, b));
}
public static int gcd(int a, int b){
int big = Math.max(a, b);
int sml = Math.min(a, b);
//base condition
if(big%sml==0){
return sml;
}
//recusive condition -> eucledian algorithm
big = big-sml;
return gcd(big, sml);
}
}