Given three numbers n, r and p, compute value of nCr mod p.
Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 1000, r = 900, p = 13 Output: 8
We strongly recommend to refer below post as a prerequisite of this.
We have introduced overflow problem and discussed Dynamic Programming based solution in above set 1. The time complexity of the DP based solution is O(n*r) and it required O(n) space. The time taken and extra space become very high for large values of n, especially values close to 109.
In this post, Lucas Theorem based solution is discussed. Time complexity of this solution is O(p2 * Logp n) and it requires only O(p) space.
For non negative integers n and r and a prime p, the following congruence relation holds:
Using Lucas Theorem for nCr % p:
Lucas theorem basically suggests that the value of nCr can be computed by multiplying results of niCri where ni and ri are individual same-positioned digits in base p representations of n and r respectively..
The idea is to one by one compute niCri for individual digits ni and ri in base p. We can compute these values DP based solution discussed in previous post. Since these digits are in base p, we would never need more than O(p) space and time complexity of these individual computations would be bounded by O(p2).
Below is implementation of above idea
Value of nCr % p is 8
Time Complexity: Time complexity of this solution is O(p2 * Logp n). There are O(Logp n) digits in base p representation of n. Each of these digits is smaller than p, therefore, computations for individual digits take O(p2). Note that these computations are done using DP method which takes O(n*r) time.
Alternate Implementation with O(p2 + Logp n) time and O(p2) space:
The idea is to precompute Pascal triangle for size p x p and store it in 2D array. All values needed would now take O(1) time. Therefore overall time complexity becomes O(p2 + Logp n).
This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Compute nCr % p | Set 3 (Using Fermat Little Theorem)
- Lucas Numbers
- Lucas Primality Test
- Sum of numbers from 1 to N which are in Lucas Sequence
- Primality Test | Set 5(Using Lucas-Lehmer Series)
- Longest sub-sequence of array containing Lucas numbers
- Rosser's Theorem
- Wilson's Theorem
- Midy's theorem
- Nicomachu's Theorem
- Fermat's Last Theorem
- Fermat's little theorem
- Compute (a*b)%c such that (a%c) * (b%c) can be beyond range
- How to compute mod of a big number?
- Compute n! under modulo p