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

Combinations n choose r function implementation More...

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

Go to the source code of this file.

Namespaces

namespace  math
 for assert
 

Functions

template<class T >
math::n_choose_r (T n, T r)
 This is the function implementation of \( \binom{n}{r} \).
 
static void test ()
 Test implementations.
 
int main (int argc, char *argv[])
 Main function.
 

Detailed Description

Combinations n choose r function implementation

A very basic and efficient method of calculating choosing r from n different choices. \( \binom{n}{r} = \frac{n!}{r! (n-r)!} \)

Author
Tajmeet Singh

Definition in file n_choose_r.cpp.

Function Documentation

◆ main()

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

Main function.

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

Definition at line 80 of file n_choose_r.cpp.

80 {
81 test(); // executing tests
82 return 0;
83}
static void test()
Test implementations.

◆ test()

static void test ( )
static

Test implementations.

Returns
void

Definition at line 52 of file n_choose_r.cpp.

52 {
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}
T n_choose_r(T n, T r)
This is the function implementation of .