TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
binomial_calculate.cpp File Reference

Program to calculate Binomial coefficients More...

#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <iostream>
Include dependency graph for binomial_calculate.cpp:

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 
namespace  binomial
 Functions for Binomial coefficients implementation.
 

Functions

size_t math::binomial::calculate (int32_t n, int32_t k)
 Function to calculate binomial coefficients.
 
static void tests ()
 Test implementations.
 
int main (int argc, const char *argv[])
 Main function.
 

Detailed Description

Program to calculate Binomial coefficients

Author
astronmax

Definition in file binomial_calculate.cpp.

Function Documentation

◆ calculate()

size_t math::binomial::calculate ( int32_t n,
int32_t k )

Function to calculate binomial coefficients.

Parameters
nfirst value
ksecond value
Returns
binomial coefficient for n and k

Definition at line 32 of file binomial_calculate.cpp.

32 {
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}
double k(double x)
Another test function.
uint64_t result(uint64_t n)

◆ main()

int main ( int argc,
const char * argv[] )

Main function.

Parameters
argccommandline argument count
argvcommandline array of arguments
Returns
0 on exit

Definition at line 79 of file binomial_calculate.cpp.

79 {
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}
static void tests()
Test implementations.
size_t calculate(int32_t n, int32_t k)
Function to calculate binomial coefficients.

◆ tests()

static void tests ( )
static

Test implementations.

Returns
void

Definition at line 56 of file binomial_calculate.cpp.

56 {
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}