I am weak in mathematics and always get stuck with the problems which require answer modulo some prime no.
eg: (500!/20!) mod 1000000007
I am familiar with BigIntegers but calculating modulo after calculating factorial of 500(even after using DP) seems to take a load of time.
I’d like to know if there’s a particular way of approaching/dealing with these kind of problems.
Here is one such problem which I am trying to solve at the moment:
http://www.codechef.com/FEB12/problems/WCOUNT
It would really be helpful if someone could direct me to a tutorial or an approach to handle these coding problems.
I am familiar with Java and C++.
The key to these large-number modulus tasks is not to compute the full result before performing the modulus. You should reduce the modulus in the intermediate steps to keep the number small:
You don’t need to reduce modulus at every single step. Just do it often enough to keep the number from getting too large.
Note that the max value of
longis 2^63 – 1. So performing 64 bit multiplications between two positive integer values (i.e. one of the operands is along) will not overflowlong. You can safely perform the remainder operation%afterwards (if that is positive as well) and cast back to an integer when required.