-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinations.cpp
57 lines (46 loc) · 1.21 KB
/
Combinations.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
* File: Combinations.cpp
* ----------------------
* This program computes the mathematical function C(n, k) from
* its mathematical definition in terms of factorial.
*/
#include <iostream>
/* Function prototypes */
int combinations(int n, int k);
int fact(int n);
/* Main program */
int main()
{
int n, k;
std::cout << "Enter the number of objects (n): ";
std::cin >> n;
std::cout << "Enter the number to be chosen (k): ";
std::cin >> k;
std::cout << "C(n, k) = " << combinations(n, k) << std::endl;
return (0);
}
/*
* Function: combinations(n, k)
* Usage: int nWays = combinations(n, k);
* --------------------------------------
* Returns the mathematical combinations function C(n, k), which is
* the number of ways one can choose k elements from a set of size n.
*/
int combinations(int n, int k)
{
return (fact(n) / (fact(k) * fact(n - k)));
}
/*
* Function: fact(n, k)
* Usage: int result = fact(n);
* ----------------------------
* Returns the factorial of n, which is the product of all the
* integers between 1 and n, inclusive.
*/
int fact(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
result *= i;
return (result);
}