Skip to content

Commit 07a5531

Browse files
Add prime factorization algorithm (TheAlgorithms#3278)
1 parent d56eaa5 commit 07a5531

File tree

2 files changed

+69
-29
lines changed

2 files changed

+69
-29
lines changed
Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
11
package com.thealgorithms.maths;
22

3-
import java.util.Scanner;
3+
/*
4+
* Authors:
5+
* (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi)
6+
* (2) Akshay Dubey (https://github.com/itsAkshayDubey)
7+
*/
8+
9+
import java.util.ArrayList;
10+
import java.util.List;
411

512
public class PrimeFactorization {
613

7-
public static void main(String[] args) {
8-
System.out.println("## all prime factors ##");
9-
Scanner scanner = new Scanner(System.in);
10-
System.out.print("Enter a number: ");
11-
int n = scanner.nextInt();
12-
System.out.print(("printing factors of " + n + " : "));
13-
pfactors(n);
14-
scanner.close();
15-
}
16-
17-
public static void pfactors(int n) {
18-
19-
while (n % 2 == 0) {
20-
System.out.print(2 + " ");
21-
n /= 2;
22-
}
23-
24-
for (int i = 3; i <= Math.sqrt(n); i += 2) {
25-
while (n % i == 0) {
26-
System.out.print(i + " ");
27-
n /= i;
28-
}
29-
}
30-
31-
if (n > 2) {
32-
System.out.print(n);
33-
}
34-
}
14+
public static List<Integer> pfactors(int n) {
15+
16+
List<Integer> primeFactors = new ArrayList<>();
17+
18+
if (n == 0) {
19+
return primeFactors;
20+
}
21+
22+
while (n % 2 == 0) {
23+
primeFactors.add(2);
24+
n /= 2;
25+
}
26+
27+
for (int i = 3; i <= Math.sqrt(n); i += 2) {
28+
while (n % i == 0) {
29+
primeFactors.add(i);
30+
n /= i;
31+
}
32+
}
33+
34+
if (n > 2) {
35+
primeFactors.add(n);
36+
}
37+
return primeFactors;
38+
}
3539
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import java.util.List;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
class PrimeFactorizationTest {
10+
11+
@Test
12+
void testpFactorsMustReturnEmptyList() {
13+
//given
14+
int n = 0;
15+
16+
//then
17+
assertTrue(PrimeFactorization.pfactors(n).isEmpty());
18+
}
19+
20+
@Test
21+
void testpFactorsMustReturnNonEmptyList() {
22+
//given
23+
int n = 198;
24+
int expectedListSize = 4;
25+
26+
//when
27+
List<Integer> actualResultList = PrimeFactorization.pfactors(n);
28+
29+
//then
30+
assertEquals(expectedListSize, actualResultList.size());
31+
assertEquals(2, actualResultList.get(0));
32+
assertEquals(3, actualResultList.get(1));
33+
assertEquals(3, actualResultList.get(2));
34+
assertEquals(11, actualResultList.get(3));
35+
}
36+
}

0 commit comments

Comments
 (0)