-
-
Save mjansen401/3bafef295d634db2004c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.List; | |
public class PrimeFactors { | |
public static List<Integer> of(int n) { | |
List<Integer> factors = new LinkedList<Integer>(); | |
for(int candidate = 2; candidate <= n; candidate++) { | |
while (n % candidate == 0) { | |
factors.add(candidate); | |
n /= candidate; | |
} | |
} | |
return factors; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import static org.junit.Assert.assertEquals; | |
import java.util.LinkedList; | |
import java.util.List; | |
import org.junit.Test; | |
public class PrimeFactorsTest { | |
@Test | |
public void itFactorsOne() { | |
assertEquals(list(), PrimeFactors.of(1)); | |
} | |
@Test | |
public void itFactorsTwo() { | |
assertEquals(list(2), PrimeFactors.of(2)); | |
} | |
@Test | |
public void itFactorsThree() { | |
assertEquals(list(3), PrimeFactors.of(3)); | |
} | |
@Test | |
public void itFactorsFour() { | |
assertEquals(list(2, 2), PrimeFactors.of(4)); | |
} | |
@Test | |
public void itFactorsEight() { | |
assertEquals(list(2,2,2), PrimeFactors.of(8)); | |
} | |
@Test | |
public void itFactorsNine() { | |
assertEquals(list(3,3), PrimeFactors.of(9)); | |
} | |
private List<Integer> list(int... factors) { | |
List<Integer> list = new LinkedList<Integer>(); | |
for (int factor : factors) | |
list.add(factor); | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment