Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to calculate nCr modulo 142857

Tags:

java

algorithm

I want to calculate nCr modulo 142857. Following is my code in Java:

private static int nCr2(int n, int r) {
    if (n == r || r == 0) {
        return 1;
    }
    double l = 1;
    if (n - r < r) {
        r = n - r;
    }
    for (int i = 0; i < r; i++) {
        l *= (n - i);
        l /= (i + 1);
    }
    return (int) (l % 142857);
}

This gives nCr in O(r) time. I want an algorithm to get the result in less time than this. Is there such an algorithm?

like image 380
Jainendra Avatar asked Dec 06 '25 08:12

Jainendra


1 Answers

You can precompute results for given n and r pairs and hard-code them in the table int t[][].

Later, during run-time, when you need nCr(n, r), you just make a look-up to this table: t[n][r].

This is O(1) during run-time.

like image 145
Adam Stelmaszczyk Avatar answered Dec 08 '25 22:12

Adam Stelmaszczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!