-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGreatestCommonDivisor.java
60 lines (43 loc) · 1.04 KB
/
GreatestCommonDivisor.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
package Dsa;
import java.util.Scanner;
public class GreatestCommonDivisor {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
gcdByBruteForce(num1,num2);
gcdByBestApproach(num1, num2);
}
/**
* Simply traverse from 1 to min(a,b) and check for every number.
* Time Complexity - O(n)
* @param num1
* @param num2
*/
private static void gcdByBruteForce(int num1, int num2) {
int ans = 1;
for(int i=1; i <= Math.min(num1, num2); i++) {
if (num1 % i == 0 && num2 % i == 0) {
ans = i;
}
}
System.out.println("GCD by Brute Force is "+ans);
}
private static void gcdByBestApproach(int num1, int num2) {
while(num1 > 0 && num2 > 0) {
if(num1 > num2) {
num1 = num1%num2;
}
else {
num2 = num2%num1;
}
}
if(num1 == 0) {
System.out.println("GCD By Best Approach is "+num2);
}
else {
System.out.println("GCD By Best Approach is "+num1);
}
}
}