Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to evaluate binomial coefficient of two integers n and k in...

How to evaluate binomial coefficient of two integers n and k in JavaScript ?

The following are the common definitions of Binomial Coefficients.

A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n. Binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects more formally, the number of k-element subsets (or k-combinations) of an n-element set.

Problem Statement: Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2.

Approach: Below are the steps to be followed in order to create a function that returns the binomial coefficient of two integers.

  • Create a function that takes to arguments n and k.
  • Now check whether the n and k are numbers. If both or one of them are not numbers then return NaN.
  • Now check if k is less than 0 or k is greater than n. If one of the statements is true then return 0.
  • Now check if the k is equal to 1 or k is equal to n. If one of the statements is true then return 1.
  • Now check if is equal to 1 or k is equal to (n-1). If one of the statements is true then return n.
  • Now write the logic to get the binomial coefficient.

Example: This example shows the above-explained approach.

Javascript




<script>
    function binomialCoefficient (n, k){
      
      // Checking if n and k are integer
      if(Number.isNaN(n) || Number.isNaN(k)){
        return NaN;
      }
      
      if(k < 0 || k > n){
        return 0
      }
      
      if(k === 0 || k === n){
        return 1
      }
      
      if(k === 1 || k === n - 1){
        return n
      }
      
      let res = n;
      for(let i = 2; i <= k; i++){
        res *= (n - i + 1) / i;
      }
      
      return Math.round(res);
    }
      
    console.log(binomialCoefficient(10, 2))
</script>


Output:

45
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments