forked from client69/Open
-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinationFormula.c
69 lines (61 loc) · 1.35 KB
/
combinationFormula.c
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
//Program for calculating Combinations.
#include<stdio.h>
//We need factorial funtion for the construction of combination function.
//Factorial: n! = n*(n-1)*(n-2)*(n-3)*...1
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
//Combination formula : nCr = n!/(r!*(n-r)!)
//Conventional function using formula:
//ITERATIVE VERSION
int comb(int n, int r)
{
int t1,t2,t3;
t1 = fact(n);
t2 = fact(r);
t3 = fact(n-r);
return t1/(t2*t3);
}
//But we know, nCr = n-1Cr-1 + n-1Cr
//RECURSIVE FORMULA
int Rcomb(int n, int r)
{
if(r==0||n==r)
return 1;
else
return Rcomb(n-1,r-1) + Rcomb(n-1,r);
}
//Such functions are called EXCESSIVE RECURSION FUNCTIONS.
//To avoid such a problem, we use MEMOIZATION. We store results of a function call so that we can utilize it again for the same function call.
//But we can use MEMOIZATION because nCr = nC(n-r)
int f[20];
int Mcomb(int n, int r)
{
if(r<=n/2)
{
if(r==0||n==r)
return 1;
else
return Mcomb(n-1,r-1) + Mcomb(n-1,r);
}
else
{
if(f[n-r]==-1)
f[n-r]=Mcomb(n,n-r);
return f[n-r];
}
}
void main()
{ int i;
for(i=0;i<20;i++)
{
f[i]=-1;
}
printf("\n%d", Mcomb(5,3));
printf("\n%d", Rcomb(5,3));
printf("\n%d", comb(5,3));
}