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
Improved By : jit_t
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Compute nCr % p | Set 3 (Using Fermat Little Theorem)
- Chinese Remainder Theorem | Set 1 (Introduction)
- Binomial Coefficient | DP-9
- Space and time efficient Binomial Coefficient
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Check if the first and last digit of the smallest number forms a prime
- Print all substring of a number without any conversion
- Complement of a number with any base b
- Check if Decimal representation of an Octal number is divisible by 7