We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 0995034 commit 058e0e3Copy full SHA for 058e0e3
1 file changed
javascript/3_math-programs/permutation.js
@@ -0,0 +1,30 @@
1
+// 20. Calculate nPr (Permutations)
2
+
3
+//P(n, r) = n! / (n - r)! for n >= r >= 0
4
5
+function permutation(n, r) {
6
+ if (n < r) return -1;
7
+ return factorial(n) / factorial(n - r);
8
+}
9
10
+function factorial(n) {
11
+ return n <= 1 ? 1 : n * factorial(n - 1);
12
13
14
+console.log(permutation(13, 2));
15
16
+// using for loop
17
18
+function permutations(n, r) {
19
+ if(n < r) return -1;
20
21
+ let result = n;
22
23
+ for(let i = 1; i < r; i++){
24
+ result *= n - i;
25
+ }
26
+ return result;
27
28
29
30
+console.log("4 P 1: ", permutation(4, 1))
0 commit comments