nCr and nPr Calculator - Problem

You need to create a calculator that computes combinations (nCr) and permutations (nPr) for given values of n and r.

Given two integers n and r, calculate:

  • nCr (combinations): The number of ways to choose r items from n items where order doesn't matter
  • nPr (permutations): The number of ways to arrange r items from n items where order matters

The formulas are:

  • nCr = n! / (r! × (n-r)!)
  • nPr = n! / (n-r)!

You must implement a factorial helper function to compute factorials, then use it to calculate both nCr and nPr.

Return an array [nCr, nPr] containing both results.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, r = 3
Output: [10, 60]
💡 Note: nCr = 5!/(3!×2!) = 120/(6×2) = 10, nPr = 5!/2! = 120/2 = 60
Example 2 — Small Values
$ Input: n = 4, r = 2
Output: [6, 12]
💡 Note: nCr = 4!/(2!×2!) = 24/(2×2) = 6, nPr = 4!/2! = 24/2 = 12
Example 3 — Edge Case r=1
$ Input: n = 6, r = 1
Output: [6, 6]
💡 Note: nCr = 6!/(1!×5!) = 720/(1×120) = 6, nPr = 6!/5! = 720/120 = 6

Constraints

  • 0 ≤ r ≤ n ≤ 20
  • n and r are non-negative integers

Visualization

Tap to expand
INPUTALGORITHMRESULTn = 5itemsr = 3chooseCalculate combinationsand permutations1factorial(5) = 1202factorial(3) = 63factorial(2) = 24nCr = 120/(6×2) = 10nPr = 120/2 = 60nCr = 10Combinations(order doesn't matter)nPr = 60Permutations(order matters)Output: [10, 60]Key Insight:A factorial helper function eliminates code duplication and makes both nCr and nPr formulas clean and maintainable.TutorialsPoint - nCr and nPr Calculator | Factorial Helper Function
Asked in
Amazon 15 Microsoft 12 Google 8
12.5K Views
Medium Frequency
~15 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen