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?
-
2https://en.wikipedia.org/wiki/Long_division – user3707125 Nov 18 '18 at 00:10
-
1What language? Many languages (e.g., Java and Python) have ways of doing this for you. – k_ssb Nov 18 '18 at 03:01
-
`as large as 10^100` is that *value of the order of…* or *number of (decimal(?)) digits of the order of 10^100* (where base conversion alone gets, well, interesting)? – greybeard Nov 18 '18 at 05:49
2 Answers
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.
-
(: ASCII ;) or char or ISO-8859 or Unicorn or whatever magic is used to represent digits `in strings`. – greybeard Nov 18 '18 at 14:20
-