w3resource

Java: Calculate the Binomial Coefficient of two positive numbers


Calculate Binomial Coefficient

From Wikipedia,

Java Exercises: Math - Binomial Coefficients


Write a Java program to calculate the Binomial Coefficient of two positive numbers.

Sample Solution:

Java Code:

import java.util.*;

class solution {

  private static long binomial_Coefficient(int n, int k)
    {
        if (k>n-k)
            k=n-k;

        long result = 1;
        for (int i=1, m=n; i<=k; i++, m--)
            result = result*m/i;
        return result;
    }

    public static void main(String[] args)
    {   
      Scanner scan = new Scanner(System.in);
       System.out.print("Input the first number(n): ");
       int n = scan.nextInt();
	   System.out.print("Input the second number(k): ");
       int k = scan.nextInt();
       if (n>0 && k>0)
		{	
		 System.out.println("Binomial Coefficient of the said numbers " + binomial_Coefficient(n, k));
		}         
   }
}

Sample Output:

Input the first number(n):  10
Input the second number(k):  2
Binomial Coefficient of the said numbers 45

Flowchart:

Flowchart: Calculate the Binomial Coefficient of two positive numbers.



For more Practice: Solve these Related Problems:

  • Write a Java program to compute the binomial coefficient using recursion with memoization for efficiency.
  • Write a Java program to calculate the binomial coefficient iteratively using Pascal’s Triangle.
  • Write a Java program to implement dynamic programming to calculate the binomial coefficient using a two-dimensional array.
  • Write a Java program to compute the binomial coefficient recursively and compare the result with an iterative approach.

Go to:


PREV : Evaluate Polynomial Efficiently.
NEXT : Taylor Series for e^x.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.