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

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

Created by Richard Zapor

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
xBD=BigDecimal(vstr);
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 )

Theory:

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

Tags

Problem Group

Solution Statistics

8 correct solutions 3 incorrect solutions
Last solution submitted on Jul 01, 2014

Solution Comments