Algorithm for dividing very large numbers

前端 未结 5 1237
夕颜
夕颜 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:32

    The easiest division algorithm to implement for large numbers is shift and subtract.

    if numerator is less than denominator then finish
    shift denominator as far left as possible while it is still smaller than numerator
    set bit in quotient for amount shifted
    subtract shifted denominator from numerator
    repeat
    the numerator is now the remainder
    

    The shifting need not be literal. For example, you can write an algorithm to subtract a left shifted value from another value, instead of actually shifting the whole value left before subtracting. The same goes for comparison.

    Long division is difficult to implement because one of the steps in long division is long division. If the divisor is an int, then you can do long division fairly easily.

提交回复
热议问题