-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathBinomialCoefficient.cpp
74 lines (47 loc) · 1.1 KB
/
BinomialCoefficient.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
#include<iostream>
using namespace std;
/*Program to find binomial coefficient C(n,k) i.e n c K-combination
C(n,k) = n! / (n-k)! . k! = fact(n) / fact(n-k)*fact(k)
*/
int fact(int n)
{
if(n<=1)
return n;
else
return n*fact(n-1);
} //Time complexity = O(n) , S(n) = O(n) required by recursion call stack
//function to find the binomial coefficient
int BinCoeff(int n,int k)
{
if(n==k)
return 1;
if(k==1)
return n;
return ( fact(n) / (fact(n-k)*fact(k)) ) ;
}//Time complexity of this method is O(n*k) , space = O(n) required by stack space
//Method-2 Efficinet solution to find binomial coefficient
int binomEfficient(int n,int k)
{
int res = 1;
if(n==k)
return 1;
if(k==1)
return n;
//if k > n-k then k = n-k as // Since C(n, k) = C(n, n-k)
if( k > n-k)
k = n-k;
//calculating C(n,k) = n!/ (n-k)! * k!
for(int i = 0 ; i < k ; i++)
{
res *= (n-i);
res /= (i+1);
}
return res;
} //Time complexity = O(k) and aux space = O(1)
int main()
{
cout<<BinCoeff(20,9);
cout<<endl;
cout<<"Efficient method"<<endl;
cout<<binomEfficient(20,12);
}