w3resource

Java: Calculate the Binomial Coefficient of two positive numbers

Java Math Exercises: Exercise-24 with Solution

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.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to compute the result from the innermost brackets.
Next: Write a Java program to calculate e raise to the power x using sum of first n terms of Taylor Series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/math/java-math-exercise-24.php