-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathlucastheorem.java
85 lines (62 loc) · 1.67 KB
/
lucastheorem.java
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
/*
This is a simple program in java language in lucas theorem. Lucas'
theorem is a result about binomial coefficients modulo a prime p.
We will be given three numbers n, r and p and we need to compute
value of nCr mod p.
*/
import java.util.*;
class lucastheorem{
// minimum return function
static int min(int x,int y){
if(x<y)
return x;
else
return y;
}
//computes the nCr % p value
static int mod(int n,int r,int p){
int[] array = new int[r+1];
array[0] = 1;
for(int i=1;i<r+1;i++){
array[i] = 0;
}
for(int i=1;i<n+1;i++){
int j = min(i,r);
while(j>0){
array[j] = (array[j]+array[j-1] )%p;
j--;
}
}
return array[r];
}
// lucas theoreme function
static int lucastheorem(int n,int r,int p){
if(r == 0){
return 1;
}
int n1 = n % p;
int r1 = r % p;
return(lucastheorem(n/p,r/p,p) * mod(n1,r1,p)) % p;
}
// driver method
public static void main(String[] args){
// taking the input from user from here
Scanner scan = new Scanner(System.in);
System.out.print("Enter The Value of n : ");
int n = scan.nextInt();
System.out.print("Enter The Value of r : ");
int r = scan.nextInt();
System.out.print("Enter The Value of p : ");
int p = scan.nextInt();
System.out.print("Value of nCr % p is ");
// calling lucastheorem
System.out.print(lucastheorem(n,r,p));
}
}
/*
Sample I/O :
Enter The Value of n : 10
Enter The Value of r : 2
Enter The Value of p : 13
Value of nCr % p is 6
*/