forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrimeFactorization.java
More file actions
40 lines (32 loc) · 848 Bytes
/
PrimeFactorization.java
File metadata and controls
40 lines (32 loc) · 848 Bytes
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
package com.thealgorithms.maths.Prime;
/*
* Authors:
* (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi)
* (2) Akshay Dubey (https://github.com/itsAkshayDubey)
*/
import java.util.ArrayList;
import java.util.List;
public final class PrimeFactorization {
private PrimeFactorization() {
}
public static List<Integer> pfactors(int n) {
List<Integer> primeFactors = new ArrayList<>();
if (n == 0) {
return primeFactors;
}
while (n % 2 == 0) {
primeFactors.add(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
primeFactors.add(i);
n /= i;
}
}
if (n > 2) {
primeFactors.add(n);
}
return primeFactors;
}
}