Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Given three numbers n, r and p, the task is to compute the value of nCr % p.
Note: p is a square-free number and the largest prime factor of p ≤ 50.
Input: n = 10, r = 2, p = 13
Explanation: 10C2 is 45 and 45 % 13= 6
Input: n = 6, r = 2, p = 13
Approach: We have already discussed several other approaches of this problem. Following is the list of the approaches:
Here we will be discussing another approach using the concept of Lucas Theorem and the Chinese Remainder Theorem. So if you are unaware of those two theorems, go through them by following the links given here.
To solve the problem follow the steps as mentioned here.
- First, find all the prime factors of p.
- Create a vector to store the nCr % m for every prime(m) in prime factors of p using the Lucas Theorem.
- Now, using Chinese remainder theorem, calculate min_x such that min_x % primes[i] = rem[i].
Below is the implementation of the above approach:
Time Complexity: O(p + log(p * n))
Auxiliary Space: O(p)
Please Login to comment...