TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
n_choose_r.cpp
Go to the documentation of this file.
1
13
#include <cassert>
14
#include <cstdint>
15
#include <iostream>
20
namespace
math
{
34
template
<
class
T>
35
T
n_choose_r
(T n, T r) {
36
if
(r > n / 2) {
37
r = n - r;
// Because of the fact that nCr(n, r) == nCr(n, n - r)
38
}
39
T ans = 1;
40
for
(
int
i = 1; i <= r; i++) {
41
ans *= n - r + i;
42
ans /= i;
43
}
44
return
ans;
45
}
46
}
// namespace math
47
52
static
void
test
() {
53
// First test on 5 choose 2
54
uint8_t t =
math::n_choose_r
(5, 2);
55
assert(((
void
)
"10 is the answer but function says otherwise.\n"
, t == 10));
56
std::cout <<
"First test passes."
<< std::endl;
57
// Second test on 5 choose 3
58
t =
math::n_choose_r
(5, 3);
59
assert(
60
((
void
)
"10 is the answer but the function says otherwise.\n"
, t == 10));
61
std::cout <<
"Second test passes."
<< std::endl;
62
// Third test on 3 choose 2
63
t =
math::n_choose_r
(3, 2);
64
assert(
65
((
void
)
"3 is the answer but the function says otherwise.\n"
, t == 3));
66
std::cout <<
"Third test passes."
<< std::endl;
67
// Fourth test on 10 choose 4
68
t =
math::n_choose_r
(10, 4);
69
assert(((
void
)
"210 is the answer but the function says otherwise.\n"
,
70
t == 210));
71
std::cout <<
"Fourth test passes."
<< std::endl;
72
}
73
80
int
main
(
int
argc,
char
*argv[]) {
81
test
();
// executing tests
82
return
0;
83
}
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
test
static void test()
Test implementations.
Definition
n_choose_r.cpp:52
math
for assert
math::n_choose_r
T n_choose_r(T n, T r)
This is the function implementation of .
Definition
n_choose_r.cpp:35
math
n_choose_r.cpp
Generated by
1.12.0