1. Out of range
Choosing fewer than 0 or more than n items is impossible, so the count is 0.
if (r < 0 || r > n) return 0Typorithm · medium
Step 1 of 8 · intro card
Math & Number Theory
Build C(n, r) iteratively: multiply by (n - i) and divide by (i + 1) for r steps, staying integer throughout.
C(n, r) counts the ways to choose r items from n, equal to n! / (r! * (n-r)!).
Computing factorials directly overflows, so the multiplicative form interleaves a multiply and a divide each step.
Multiplying by (n - i) before dividing by (i + 1) keeps the running result an exact integer; using min(r, n-r) cuts the loop count.
Loop r = min(r, n-r) times.
Multiply by (n - i), divide by (i + 1).
Each partial product is exact.
function nCr(n, r) {
if (r < 0 || r > n) return 0;
if (r > n - r) r = n - r;
let result = 1;
for (let i = 0; i < r; i += 1) {
result = (result * (n - i)) / (i + 1);
}
return result;
}Connect each part of the code to the concept before you type.
Choosing fewer than 0 or more than n items is impossible, so the count is 0.
if (r < 0 || r > n) return 0C(n, r) = C(n, n-r), so loop the smaller of r and n-r for fewer iterations.
if (r > n - r) r = n - rMultiply by the next numerator (n-i) then divide by (i+1); the running product stays an exact integer.
result = (result * (n - i)) / (i + 1)The product needs exactly r factor pairs to build C(n, r).
for (let i = 0; i < r; i += 1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputC(5, 2)
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state