java - Calculate C(n, k) combinations for big numbers using modInverse -


i want calculate combinations c(n, k) n , k large. tried using modular inverse following, it's not giving correct output small numbers. can tell me i'm wrong?

import java.math.biginteger;  public class test {      public static int[] factorials = new int[100001];     public static int mod = 1000000007;     public static biginteger mod = biginteger.valueof(1000000007);      public static void calculatefactorials() {          long f = 1;          (int = 1; < factorials.length; i++) {             f = (f * i) % mod;             factorials[i] = (int) f;         }      }      // choose(n, k) = n! / (k! * (n-k)!)     public static long nck(int n, int k) {          if (n < k) {             return 0;         }          long = biginteger.valueof(k).modinverse(mod).longvalue();         long b = biginteger.valueof(n - k).modinverse(mod).longvalue();          // left right associativity between * , %         return factorials[n] * % mod * b % mod;      }      public static void main(string[] args) {          calculatefactorials();         system.out.println(nck(5, 2));      }  } 

the lines

    long = biginteger.valueof(k).modinverse(mod).longvalue();     long b = biginteger.valueof(n - k).modinverse(mod).longvalue(); 

should be

    long = biginteger.valueof(factorials[k]).modinverse(mod).longvalue();     long b = biginteger.valueof(factorials[n - k]).modinverse(mod).longvalue(); 

you might consider caching inverse factorials factorials.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -