Falling factorial JAVA

Viewed 160

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.

1 Answers

One thing that immediately caught my attention was that your code doesn't really handle the case where n is 0. Basically both of your if statements are skipped, so you return 0. However this seems wrong to me, since 0! = 1. Notice in the code you found online, this is accounted for. So with your code fallingFactorial(0, 1) is 0, and with the online code fallingFactorial(0, 1) is 1.

Related