-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathncr.txt
88 lines (52 loc) · 1.21 KB
/
ncr.txt
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
Given three integers A, B, and C, where A represents n, B represents r, and C represents m, find and return the value of nCr % m where nCr % m = (n!/((n-r)!*r!))% m.
x! means factorial of x i.e. x! = 1 * 2 * 3... * x.
Problem Constraints
1 <= A * B <= 106
1 <= B <= A
1 <= C <= 106
Input Format
The first argument given is integer A ( = n).
The second argument given is integer B ( = r).
The third argument given is integer C ( = m).
Output Format
Return the value of nCr % m.
Example Input
Input 1:
A = 5
B = 2
C = 13
Input 2:
A = 6
B = 2
C = 13
Example Output
Output 1:
10
Output 2:
2
Example Explanation
Explanation 1:
The value of 5C2 % 11 is 10.
Explanation 2:
The value of 6C2 % 13 is 2.
Solution:
int Solution::solve(int A, int B, int C) {
int ncr[A+1][B+1];
for (int i=0; i<=A; i++){
for (int j=0; j<=B; j++){
/*if (i==0){
ncr[i][j]=0;
}*/
if ((j==0)|| (i==j)){
ncr[i][j]=1;
}
else if (j==1){
ncr[i][j]=i;
}
else {
ncr[i][j]=(ncr[i-1][j-1] + ncr[i-1][j])%C;
}
}
}
return ncr[A][B]%C;
}