Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 300,419 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,505 people online right now. Registration is fast and FREE... Join Now!





Computing the Binomal Coefficient (a dynamic programming approach)

just a small snippet to compute the binomial Coefficient nCk.. mathematically to compute the binomial coefficient ncK = n!/k!(n-k)! but if n is too large, computing it will be very inefficient, instead there's a recursive formula nCk = (n-1)C(k-1)+(n-1)Ck, so this can be used in a dynamic programming approach...also to speed things up, binomial Coefficients have this identity that nCk = nC(n-k), so we can use this to minimize the number of terms computed

Submitted By: mostyfriedman
Actions:
Rating:
Views: 258

Language: Java

Last Modified: July 18, 2009

Snippet


  1. public static long binomialCoefficient(int n, int k)
  2. {
  3.                 if(n - k == 1 || k == 1)
  4.                         return n;
  5.  
  6.                 long [][] b = new long[n+1][n-k+1];
  7.                 b[0][0] = 1;
  8.                 for(int i = 1; i < b.length; i++)
  9.                 {
  10.                         for(int j = 0; j < b[i].length; j++)
  11.                         {
  12.                                 if(i == j || j == 0)       
  13.                                         b[i][j] = 1;
  14.                                 else if(j == 1 || i - j == 1)
  15.                                         b[i][j] = i;
  16.                                 else
  17.                                         b[i][j] = b[i-1][j-1] + b[i-1][j];
  18.                         }
  19.                 }
  20.                 return b[n][n-k];
  21. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month