-
Notifications
You must be signed in to change notification settings - Fork 14
/
Computing_binomial_coefficients.cpp
87 lines (77 loc) · 1.9 KB
/
Computing_binomial_coefficients.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <array>
#include <cassert>
#include <iostream>
#include <random>
#include <vector>
using std::array;
using std::cout;
using std::default_random_engine;
using std::endl;
using std::random_device;
using std::uniform_int_distribution;
using std::vector;
// @include
int compute_binomial_coefficients(int n, int k) {
array<vector<int>, 2> table = {vector<int>(k + 1), vector<int>(k + 1)};
table[0][0] = 1;
// C(i, j) = C(i - 1, j) + C(i - 1, j - 1).
for (int i = 1; i <= n; ++i) {
table[i & 1][0] = 1; // special case: one way to select zero element.
for (int j = 1; j <= i && j <= k; ++j) {
table[i & 1][j] = table[(i - 1) & 1][j] + table[(i - 1) & 1][j - 1];
}
}
return table[n & 1][k];
}
// @exclude
int check_ans(int n, int k) {
vector<int> number;
for (int i = 0; i < k; ++i) {
number.emplace_back(n - i);
}
vector<int> temp;
for (int i = 2; i <= k; ++i) {
bool find = false;
for (int& a : number) {
if ((a % i) == 0) {
a /= i;
find = true;
break;
}
}
if (find == false) {
temp.emplace_back(i);
}
}
int res = 1;
for (const int& a : number) {
res *= a;
}
for (const int& a : temp) {
res /= a;
}
return res;
}
int main(int argc, char* argv[]) {
default_random_engine gen((random_device())());
for (int times = 0; times < 1000; ++times) {
int n, k;
if (argc == 3) {
n = atoi(argv[1]), k = atoi(argv[2]);
} else {
uniform_int_distribution<int> n_dis(1, 21);
n = n_dis(gen);
uniform_int_distribution<int> k_dis(0, n);
k = k_dis(gen);
}
int res = compute_binomial_coefficients(n, k);
cout << "res = " << res << endl;
assert(res == check_ans(n, k));
cout << n << " out of " << k << " = " << res << endl;
if (argc == 3) {
break;
}
}
return 0;
}