Algorithm for dividing very large numbers

前端 未结 5 1258
夕颜
夕颜 2020-12-06 01:41

I need to write an algorithm(I cannot use any 3rd party library, because this is an assignment) to divide(integer division, floating parts are not important) very large numb

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 02:41

    I'd imagine that dividing the 'long' way like in grade school would be a potential route. I'm assuming you are receiving the original number as a string, so what you do is parse each digit. Example:

    Step 0:

       /-----------------
    13 | 453453453435....
    

    Step 1: "How many times does 13 go into 4? 0

         0
       /-----------------
    13 | 453453453435....
    

    Step 2: "How many times does 13 go into 45? 3

         03
       /-----------------
    13 | 453453453435....
       - 39
         --
          6
    

    Step 3: "How many times does 13 go into 63? 4

    etc etc. With this strategy, you can have any number length and only really have to hold enough digits in memory for an int (divisor) and double (dividend). (Assuming I got those terms right). You store the result as the last digit in your result string.

    When you hit a point where no digits remain and the calculation wont go in 1 or more times, you return your result, which is already formatted as a string (because it could be potentially larger than an int).

提交回复
热议问题