-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestMultiple.java
More file actions
50 lines (47 loc) · 1.62 KB
/
Copy pathSmallestMultiple.java
File metadata and controls
50 lines (47 loc) · 1.62 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
import java.io.*;
import java.util.*;
class SmallestMultiple {
public static Set<Integer> primes = new HashSet<Integer>();
public static List<Integer> primeFactors = new ArrayList<Integer>();
public static void main (String[] args) {
int bottomRange = Integer.parseInt(args[0]);
int topRange = Integer.parseInt(args[1]);
// find all prime factors of numbers in the range
// and multiply them together
for (int i = bottomRange; i <= topRange; ++i) {
// find the prime factors of i
if (isPrime(i)) {
primes.add(i);
primeFactors.add(i);
continue;
}
// if not a prime, divide i into prime factors
int n = i;
List<Integer> tempFactors = new ArrayList<Integer>(primeFactors);
List<Integer> addToPrimeFactors = new ArrayList<Integer>();
for (Integer p : primes) {
while (n % p == 0) {
n /= p;
if (!tempFactors.remove(p)) {
addToPrimeFactors.add(p);
}
}
}
primeFactors.addAll(addToPrimeFactors);
}
int smallestMultiple = 1;
for (Integer n : primeFactors) {
smallestMultiple *= n;
}
System.out.println(smallestMultiple);
}
// excluding 1 as a prime for ease
public static boolean isPrime(int n) {
for (Integer p : primes) {
if (n % p == 0) {
return false;
}
}
return n == 1 ? false : true;
}
}