templates/combinatorics-counting.cpp
compilable
$cat templates/combinatorics-counting
Combinatorics Counting
Non-modular nCr, nPr, and Legendre's formula for prime power in factorials.
#nCr#nPr#factorial#legendre#combinatorics
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll nCr(ll n, ll r) {
if (r < 0 || r > n) return 0;
if (r == 0 || r == n) return 1;
if (n - r < r) r = n - r;
ll res = 1;
for (ll i = 0; i < r; i++) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
ll nPr(ll n, ll r) {
if (r < 0 || r > n) return 0;
ll res = 1;
for (ll i = 0; i < r; i++)
res *= (n - i);
return res;
}
ll factorialPrimePower(ll n, ll p) {
ll cnt = 0;
for (ll pk = p; pk <= n; pk *= p)
cnt += n / pk;
return cnt;
}30 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Combinatorics Counting
Non-modular combinatorial functions for small values.
Functions
- Returns 1 for , , and
- Returns 0 for or
When to Use
ll (roughly ). For large with mod, use the Binomial Coefficients template instead