2

If I have two numbers A and B and I want to compute A%B for A and B are very large (as large as 10^100), both are stored in strings, how can I achieve that?

2 Answers2

1

10^100 is actually not that large, so you can just use a language like Python, which do not have an explicitly defined limit on the size of long integers.

If you want to just do the calculation once, you can just use a big number calculator like here.

Sharat
  • 147
  • 7
1

If you want to work this out for fun, you can implement the division algorithm directly on the string representation.

Addition of two numbers is not a big deal (from right to left, add the ASCII values and deduct that of 0; carry if necessary). Subtraction is similar. And the comparison of two numbers is also very similar.

Multiplication of a number by a digit is also manageable (from right to left, convert ASCII->digit, perform the multiply and convert the rightmost digit to ASCII; carries can be larger but will fit in an int).

The key operation is: given a dividend and a divisor, find the leftmost digit of the quotient.

E.g.

3452 : 27

27 fits once in 34, hence the first digit is 1. Now subtract and get the next digit

 3452
-27
= 752

27 fits 2 times in 75, and

 752
-54
=212

Finally, 27 fits 7 times in 212 and

 212
-189
= 23

which is the remainder.