Multiplication of very long integers

后端 未结 7 1759
日久生厌
日久生厌 2021-02-09 05:57

Is there an algorithm for accurately multiplying two arbitrarily long integers together? The language I am working with is limited to 64-bit unsigned integer length (maximum int

7条回答
  •  臣服心动
    2021-02-09 06:52

    Most languages have functions or libraries that do this, usually called a Bignum library (GMP is a good one.)

    If you want to do it yourself, I would do it the same way that people do long multiplication on paper. To do this you could either work with strings containing the number, or do it in binary using bitwise operations.

    Example:

      45
     x67
     ---
     315
    +270
    ----
     585
    

    Or in binary:

       101
      x101
      ----
       101
      000
    +101
    ------
     11001
    

    Edit: After doing it in binary I realized that it would be much simpler (and faster of course) to code using bitwise operations instead of strings containing the base-10 numbers. I've edited my binary multiplying example to show a pattern: for each 1-bit in the bottom number, add the top number, bit-shifted left the position of the 1-bit times to a variable. At the end, that variable will contain the product.

    To store the product, you'll have to have two 64-bit numbers and imagine one of them being the first 64 bits and the other one the second 64 bits of the product. You'll have to write code that carries the addition from bit 63 of the second number to bit 0 of the first number.

提交回复
热议问题