So basically I need to write a method that calculates a falling factorial. "The falling power 10 5 would equal 10 * 9 * 8 * 7 * 6 = 30240"
so here is my 1st try:
public static long fallingPower(int n, int k) {
long holder = n;
int counter;
if (n > 0) {
counter = 1;
for (int i = k - 1; i > 0; i--) {
holder = holder * (n - counter);
counter++;
}
}
if (n < 0) {
counter = -1;
for (int i = k - 1; i > 0; i--) {
holder = holder * (n + counter);
counter--;
//System.out.println(holder);
}
}
return holder;
}
It works with tests like (10, 5) (-4, 5) and (8, 3) given in the problem context but it fails the actual test.
After a long session of wolfram alfa readings and a bit of googling this passes the test:
public static long fallingPower(int n, int k) {
long count, holder;
holder = 1;
for (count = 0; count <= k - 1; count = count + 1) {
holder = holder * (n - count);
}
return holder;
}
My question is, what exactly did I do wrong in the first case that led to the correct sample test but would result in incorrect output given larger input.
Thank you very much.