w3resource

JavaScript: Calculate the combination of n and r

JavaScript Math: Exercise-42 with Solution

Write a JavaScript function to calculate the combination of n and r.
The formula is : n!/(r!*(n - r)!).

Test Data :
console.log(combinations(6, 2));
15
console.log(combinations(5, 3));
10

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to calculate the combination of n and r. The formula is : n!/(r!*(n - r)!)</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function product_Range(a,b) {
  var prd = a,i = a;
 
  while (i++< b) {
    prd*=i;
  }
  return prd;
}


function combinations(n, r) 
{
  if (n==r || r==0) 
  {
    return 1;
  } 
  else 
  {
    r=(r < n-r) ? n-r : r;
    return product_Range(r+1, n)/product_Range(1,n-r);
  }
}


console.log(combinations(6, 2));
console.log(combinations(5, 3));

Sample Output:

15
10

Flowchart:

Flowchart: JavaScript Math- Calculate the combination of n and r

Live Demo:

See the Pen javascript-math-exercise-42 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to count the digits of an integer.
Next: Write a JavaScript function to get all prime numbers from 0 to a specified number

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.