How to useRecursion in Javascript
In this approach, we will first calculate the factorial of the given number using recursion and then create a function named “permutation” to calculate and return the division of n factorial with (n-r) factorial.
function factorial(n) {
if (n <= 1) return 1
return n * factorial(n - 1)
}
function permutation(n, r) {
if (n < r) return -1
return factorial(n) / factorial(n - r)
};
Example: In this example, factorial to find the factorial of a number and permutation to calculate nPr (permutations). and permutation function to calculate permutations, denoted as “nPr,” where “n” represents the total number of items, and “r” represents the number of items selected at a time.
Javascript
function factorial(n) { if (n <= 1) return 1 return n * factorial(n - 1) } function permutation(n, r) { if (n < r) return -1 return factorial(n) / factorial(n - r) } console.log( "4 P 1: " , permutation(4, 1)) console.log( "13 P 2: " , permutation(13, 2)) |
4 P 1: 4 13 P 2: 156
JavaScript Program to Calculate nPr (Permutations)
In this article, we are going to learn how to calculate permutations (nPr) by using JavaScript. Calculating nPr, or permutations means finding the number of unique ordered arrangements of r items from a set of n distinct items. Where order matters and no item is repeated.
The formula for calculating permutations is n factorial divided by (n-r) factorial where n and r are integers and n is greater than or equal to r. The mathematical representation is as follows:
P(n, r) = n! / (n - r)!
For n ≥ r ≥ 0
There are several methods that can be used to Calculating nPr (Permutations) by using javascript, which are listed below:
Table of Content
- Using Recursion
- Using for Loop
We will explore all the above methods along with their basic implementation with the help of examples.
Contact Us