Problem 1855. Usage of java.math : N Choose K with unlimited precision

Calculate the binomial coefficient nchoosek with full accuracy. This challenge may use the wonderful word of java.math that allows unlimited precision calculations. The primary reference sites are Java Math, Java BigDecimal, and Java BigInteger.

The usage of BigDecimal functions add, multiply, and divide may be required.

Java Math:

vd-decimal value, vstr-string, vi-integer value 
xBD=java.math.BigDecimal(vd);  % valid vd,vstr,vi creates xBD a BigDecimal variable
import java.math.*;  % simplifies statements
xplusyBD=xBD.add(BigDecimal(y)); % add input requires BD type
xmultiplyzBD=xBD.multiply(BigDecimal(z));  % multiply input requires BD type
xdividezBD=xBD.divide(BigDecimal(z));  % divide input requires BD type
xmultydivz=xBD.multiply(yBD).divide(zBD);  out=x*y/z
To convert java to string of unlimited length can be achieved via java toString or Matlab char
xstr=toString(xBD)  or xstr=char(xBD) 

Input: [N,K] [ Inputs to nchoosek(N,K) 0<=K<=N<200 ]

Output: C (char variable of C=nchoosek(n,k) or BigDecimal variable type )


C(n,k) link shows multiple evaluation methods.

C(n,k)= n!/(k!(n-k)!)

The factorial method gives a direct solution while the multiplicative may require fewer operations.

Hint: C(5,3)=(5/3)*(4/2)*(3/1)= (5/1)*(4/2)*(3/3); numerator has k terms

Future Challenges:

1. Usage of java.math

2. nchoosek_large (full precision)
3. Next Prime
4. factor_large

5. Factorial

Solution Stats

65.22% Correct | 34.78% Incorrect
Last solution submitted on Oct 14, 2015

Solution Comments

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!