File tree Expand file tree Collapse file tree 2 files changed +69
-29
lines changed
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree 2 files changed +69
-29
lines changed Original file line number Diff line number Diff line change 11package 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
512public 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}
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments