Skip to content

Instantly share code, notes, and snippets.

@mjansen401 mjansen401/PrimeFactors.java Secret

Created Jul 15, 2013
Embed
What would you like to do?
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;
}
}
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
You can’t perform that action at this time.