I had to use this for the kyu 3 binomial expansion kata since I have no clue how to use the BigInts library for Java. Instead of calculating the total value of each factorial, this finds the factors of the numerator and denominator, simplifies, and divides the results. Nothing special and there are better solutions, but I'm proud of it.
Note: The n-choose-k formula
n!
------------
k!(n - k)!
public class ArrayFactorial{
public static int factorial(int n, int k) {
int n_k = n - k;
int[] numerator = new int[n];
int[] denominator = new int[k + n_k];
for(int i = 1; i <= n; i++)
numerator[i - 1] = i;
for(int i = 1; i <= k; i++)
denominator[i - 1] = i;
for(int i = 1; i <= n_k; i++)
denominator[k + i - 1] = i;
for(int i = 0; i < numerator.length; i++){
for(int j = 0; j < denominator.length; j++){
if(numerator[i] == denominator[j]) {
numerator[i] = 1;
denominator[j] = 1;
}
}
}
int n_sum = 1;
int d_sum = 1;
for(int v : numerator)
n_sum *= v;
for(int v : denominator)
d_sum *= v;
return n_sum / d_sum;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
// TODO: Replace examples and use TDD by writing your own tests
public class SolutionTest {
@Test
public void BasicTests() {
assertEquals(3, ArrayFactorial.factorial(3, 1));
assertEquals(10, ArrayFactorial.factorial(5, 2));
assertEquals(15, ArrayFactorial.factorial(6, 4));
}
@Test
public void LargerTests() {
assertEquals(1365, ArrayFactorial.factorial(15, 4));
assertEquals(19448, ArrayFactorial.factorial(17, 7));
}
}