Skip to content

Instantly share code, notes, and snippets.

@mjansen401
Created July 15, 2013 18:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjansen401/3bafef295d634db2004c to your computer and use it in GitHub Desktop.
Save mjansen401/3bafef295d634db2004c to your computer and use it in GitHub Desktop.
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