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:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join