I recently encountered this problem in a C++ program running on a 32-bit UNIX platform. The problem was that the number was 28 digits long and no native datatype in C++ could store a number of that sizenot even unsigned long long
or long double
could help; they were only eight bytes long.
A divide-and-conquer strategy can be used in this casethe entire number doesn't have to be processed in one go. Divide the number into smaller numbers, then find the remainders of these smaller numbers. Add up the remainders and repeat the process. As long as the remainders are retained, the final answer wont change.
Suppose you need to find nBig % a:
- Take a manageable portion (say, x) of the input large number (nBig) and subtract it from nBig (nBig = nBig - x).
- Compute the mod of x (mod = x % a).
- Add the mod to nBig (nBig = nBig + mod). This way, the number nBig can be reduced without affecting the actual answer.
This first example uses small numbers, so it's easy to follow the logic. To find 27 % 8:
- Let x = 17. Thus, nBig = nBig - x = 27-17 = 10.
- mod = x % a = 17 % 8 = 1
- nBig = nBig + mod = 10 + 1 = 11
- Thus, nBig is reduced from 27 to 11 without affecting the answer, which is 3.
But what about finding the mod
of large numbers? Extend the same logic, and the above problem can be solved as follows:
- Let the input be:
- nBig: This is a string representing a 30 digit large number (for example, 123456789033333333335555555555)
- a: Integer (for example, 320)
- To find nBig % a:
- Iteration 1:
- Extract few digits from the LHS of nBig. Thus, tmp = 1234567890 and nBig = 33333333335555555555.
- Find mod of tmp:
mod = tmp % a = 210
- Prefix mod to nBig:
nBig = 21033333333335555555555
- Iteration 2:
- tmp = 2103333333 and nBig = 3335555555555
- mod = tmp % a = 213
- nBig = 2133335555555555
- Iteration 3:
- tmp = 2133335555 and nBig = 555555
- mod = tmp % a = 195
- nBig = 195555555
- Iteration 4:
- tmp = 195555555 and nBig = ""
- mod = tmp % a = 35
- The Answer = 35.
What follows is the pseudo code for finding nBig % a. First, let d = the number of digits that can be processed at a time. Then, repeat while val( nBig ) >= a.
- tmpStr: Equals d digits from the LHS of nBig.
- nBig: Equals the remaining portion of nBig.
- tmpNum: Equals toInteger(tmpStr).
- tmpNum: Equals tmpNum % a.
- tmpStr: Equals toString(tmpNum).
- nBig: Equals tmpStr + nBig.
To select d
, make sure d
satisfies the following constraint: The maximum number of digits in Mod a < d <
should equal the maximum tmpNum
minus the maximum number of digits in Mod
For example, suppose you have a = 512 (Mod ranges 0..511), and your tmpNum can store a maximum of 16 digits. Then, you'd have:
3 < d <= 16-3)
In another example, suppose a = 100 (Mod ranges 0..99)
, and tmpNum
can store a maximum of 16 digits. In that case, you'd have:
2 < d <= 16-2)