TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binomial_calculate.cpp
Go to the documentation of this file.
1
8
9
#include <cassert>
10
#include <cstdint>
11
#include <cstdlib>
12
#include <iostream>
13
18
namespace
math
{
25
namespace
binomial
{
32
size_t
calculate
(int32_t n, int32_t k) {
33
// basic cases
34
if
(k > (n / 2))
35
k = n - k;
36
if
(k == 1)
37
return
n;
38
if
(k == 0)
39
return
1;
40
41
size_t
result = 1;
42
for
(int32_t i = 1; i <= k; ++i) {
43
result *= n - k + i;
44
result /= i;
45
}
46
47
return
result;
48
}
49
}
// namespace binomial
50
}
// namespace math
51
56
static
void
tests
() {
57
// tests for calculate function
58
assert(
math::binomial::calculate
(1, 1) == 1);
59
assert(
math::binomial::calculate
(57, 57) == 1);
60
assert(
math::binomial::calculate
(6, 3) == 20);
61
assert(
math::binomial::calculate
(10, 5) == 252);
62
assert(
math::binomial::calculate
(20, 10) == 184756);
63
assert(
math::binomial::calculate
(30, 15) == 155117520);
64
assert(
math::binomial::calculate
(40, 20) == 137846528820);
65
assert(
math::binomial::calculate
(50, 25) == 126410606437752);
66
assert(
math::binomial::calculate
(60, 30) == 118264581564861424);
67
assert(
math::binomial::calculate
(62, 31) == 465428353255261088);
68
69
std::cout <<
"[+] Binomial coefficients calculate test completed"
70
<< std::endl;
71
}
72
79
int
main
(
int
argc,
const
char
* argv[]) {
80
tests
();
// run self-test implementations
81
82
if
(argc < 3) {
83
std::cout <<
"Usage ./binomial_calculate {n} {k}"
<< std::endl;
84
return
0;
85
}
86
87
int32_t n = atoi(argv[1]);
88
int32_t k = atoi(argv[2]);
89
90
std::cout <<
math::binomial::calculate
(n, k) << std::endl;
91
return
0;
92
}
tests
static void tests()
Test implementations.
Definition
binomial_calculate.cpp:56
math::binomial::calculate
size_t calculate(int32_t n, int32_t k)
Function to calculate binomial coefficients.
Definition
binomial_calculate.cpp:32
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
binomial
Functions for Binomial coefficients implementation.
math
for assert
math
binomial_calculate.cpp
Generated by
1.13.2