-
Notifications
You must be signed in to change notification settings - Fork 28
/
PrimeFactorsDemo.java
54 lines (40 loc) · 1.05 KB
/
PrimeFactorsDemo.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
package ds_001_intro;
import java.util.LinkedList;
import java.util.List;
public class PrimeFactorsDemo {
public static void main(String[] args) {
// int number = 204;
long number = 123456789012345678L;
List<Long> primeFactors = getPrimeFactors(number);
System.out.println("Prime Factors of " + number);
printLongArray(primeFactors);
}
private static List<Long> getPrimeFactors(long number) {
List<Long> factors = new LinkedList<>();
long factor = 2;
while(number % factor == 0) {
factors.add(factor);
number /= factor;
}
factor = 3;
int stopAt = (int) Math.sqrt(number);
while(factor <= stopAt) {
while(number % factor == 0) {
factors.add(factor);
number /= factor;
stopAt = (int)Math.sqrt(number);
}
factor += 2;
}
if(number > 1) {
factors.add(number);
}
return factors;
}
private static void printLongArray(List<Long> primeFactors) {
for(int i = 0; i < primeFactors.size(); i++) {
System.out.printf("%3d ", primeFactors.get(i));
}
System.out.printf("\n");
}
}