Add prime factorization algorithm (#3278)

This commit is contained in:
Akshay Dubey 2022-09-22 00:59:20 +05:30 committed by GitHub
parent d56eaa58af
commit 07a5531f1a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 25 deletions

View File

@ -1,35 +1,39 @@
package com.thealgorithms.maths;
import java.util.Scanner;
/*
* 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 class PrimeFactorization {
public static void main(String[] args) {
System.out.println("## all prime factors ##");
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
System.out.print(("printing factors of " + n + " : "));
pfactors(n);
scanner.close();
}
public static List<Integer> pfactors(int n) {
List<Integer> primeFactors = new ArrayList<>();
public static void pfactors(int n) {
if (n == 0) {
return primeFactors;
}
while (n % 2 == 0) {
System.out.print(2 + " ");
n /= 2;
}
while (n % 2 == 0) {
primeFactors.add(2);
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
System.out.print(i + " ");
n /= i;
}
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i == 0) {
primeFactors.add(i);
n /= i;
}
}
if (n > 2) {
System.out.print(n);
}
}
if (n > 2) {
primeFactors.add(n);
}
return primeFactors;
}
}

View File

@ -0,0 +1,36 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
class PrimeFactorizationTest {
@Test
void testpFactorsMustReturnEmptyList() {
//given
int n = 0;
//then
assertTrue(PrimeFactorization.pfactors(n).isEmpty());
}
@Test
void testpFactorsMustReturnNonEmptyList() {
//given
int n = 198;
int expectedListSize = 4;
//when
List<Integer> actualResultList = PrimeFactorization.pfactors(n);
//then
assertEquals(expectedListSize, actualResultList.size());
assertEquals(2, actualResultList.get(0));
assertEquals(3, actualResultList.get(1));
assertEquals(3, actualResultList.get(2));
assertEquals(11, actualResultList.get(3));
}
}