Skip to content

Commit 27ae9d3

Browse files
Merge pull request matthewsamuel95#822 from paolaguarasci/binomialCPP
binomial coeff in cpp
2 parents 496534c + 51adf48 commit 27ae9d3

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Binomial Coeff
3+
*/
4+
5+
#include <iostream>
6+
#include <climits>
7+
#include <stdlib.h>
8+
using namespace std;
9+
10+
int fact(int);
11+
int coeff(int, int);
12+
bool check(char **, char **);
13+
bool isNum(char *c);
14+
15+
int main(int argc, char *argv[])
16+
{
17+
18+
if (argc != 3 || check(&argv[1], &argv[2]))
19+
{
20+
cout << "How to use\n\t$ ./bc n k\nwith n,k positive integer and n >= k." << endl;
21+
return -1;
22+
}
23+
24+
int n = atoi(argv[1]);
25+
int k = atoi(argv[2]);
26+
27+
cout << "With n = " << n
28+
<< " and k = " << k
29+
<< " the binomial coeffivients is "
30+
<< coeff(n, k)
31+
<< endl;
32+
33+
return 0;
34+
}
35+
36+
int fact(int n)
37+
{
38+
if (n == 1 || n == 0)
39+
{
40+
return 1;
41+
}
42+
return n * fact(n - 1);
43+
}
44+
45+
int coeff(int n, int k)
46+
{
47+
return fact(n) / (fact(k) * fact(n - k));
48+
}
49+
50+
bool check(char **n, char **k)
51+
{
52+
if ((!isNum(*n) || !isNum(*k)) || atoi(*n) < atoi(*k) || (atoi(*n) < 0 || atoi(*k) < 0))
53+
{
54+
return true;
55+
}
56+
return false;
57+
}
58+
59+
bool isNum(char *c)
60+
{
61+
for (int i = 0; c[i]; i++)
62+
{
63+
if (!isdigit(c[i]))
64+
{
65+
return false;
66+
}
67+
}
68+
return true;
69+
}

0 commit comments

Comments
 (0)