-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindLCM.java
More file actions
70 lines (43 loc) · 1.4 KB
/
FindLCM.java
File metadata and controls
70 lines (43 loc) · 1.4 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
62
63
64
65
66
67
68
69
70
public class FindLCM{
public static void main (String... args){
int[] numbers = {2,9,5,6,6};
try{
System.out.println(findLCMOfMoreThanTwoNumbers(numbers));
}
catch(Exception exception){
System.out.println("None of the numbers can be lesser than one");
}
}
public static int findGCDOfTwoNumbers(int numberOne, int numberTwo){
int gcd = 0;
int minimum = numberOne;
if(numberTwo < minimum) minimum = numberTwo;
for(int count = minimum; count >= 1; count--){
if( numberTwo % count == 0 && numberOne % count == 0 ){
gcd = count;
break;
}
}
return gcd;
}
public static int findGCDForMoreThanTwoNumbers(int[] numbers){
int gcd = findGCDOfTwoNumbers(numbers[0], numbers[1]);
for(int index = 2; index < numbers.length; index++){
gcd = findGCDOfTwoNumbers(gcd, numbers[index]);
}
return gcd;
}
public static int findLCMOfTwoNumbers(int numberOne, int numberTwo){
int multiples = numberOne * numberTwo;
int lcm = multiples/findGCDOfTwoNumbers(numberOne, numberTwo);
return lcm;
}
public static int findLCMOfMoreThanTwoNumbers(int[] numbers){
for(int number : numbers) if (number < 1) throw new IllegalArgumentException("Number cannot be lower than 1");
int lcm = findLCMOfTwoNumbers(numbers[0], numbers[1]);
for(int index = 2; index < numbers.length; index++){
lcm = findLCMOfTwoNumbers(lcm, numbers[index]);
}
return lcm;
}
}