-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
binomial.cpp
69 lines (58 loc) · 1.03 KB
/
binomial.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
/*
Binomial Coeff
*/
#include <iostream>
#include <climits>
#include <stdlib.h>
using namespace std;
int fact(int);
int coeff(int, int);
bool check(char **, char **);
bool isNum(char *c);
int main(int argc, char *argv[])
{
if (argc != 3 || check(&argv[1], &argv[2]))
{
cout << "How to use\n\t$ ./bc n k\nwith n,k positive integer and n >= k." << endl;
return -1;
}
int n = atoi(argv[1]);
int k = atoi(argv[2]);
cout << "With n = " << n
<< " and k = " << k
<< " the binomial coeffivients is "
<< coeff(n, k)
<< endl;
return 0;
}
int fact(int n)
{
if (n == 1 || n == 0)
{
return 1;
}
return n * fact(n - 1);
}
int coeff(int n, int k)
{
return fact(n) / (fact(k) * fact(n - k));
}
bool check(char **n, char **k)
{
if ((!isNum(*n) || !isNum(*k)) || atoi(*n) < atoi(*k) || (atoi(*n) < 0 || atoi(*k) < 0))
{
return true;
}
return false;
}
bool isNum(char *c)
{
for (int i = 0; c[i]; i++)
{
if (!isdigit(c[i]))
{
return false;
}
}
return true;
}