简体   繁体   中英

Falling factorial JAVA

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM