Split Multiplication of integers

前端 未结 4 1742
挽巷
挽巷 2020-12-20 07:52

I need an algorithm that uses two 32-bit integers as parameters, and returns the multiplication of these parameters split into two other 32-bit integers: 32-highest-bits par

相关标签:
4条回答
  • 2020-12-20 08:29

    Just use 16 bits digits.

    void multiply(uint32_t a, uint32_t b, uint32_t* h, uint32_t* l) {
        uint32_t const base = 0x10000;
        uint32_t al = a%base, ah = a/base, bl = b%base, bh = b/base;
        *l = al*bl;
        *h = ah*bh;
        uint32_t rlh = *l/base + al*bh;
        *h += rlh/base;
        rlh = rlh%base + ah*bl;
        *h += rlh/base;
        *l = (rlh%base)*base + *l%base;
    }
    
    0 讨论(0)
  • 2020-12-20 08:34

    This is the explanation and an implementation of the Karatsubas-Algorithm. I have downloaded the code and ran it several times. It seems that it's doing well. You can modify the code according to your need.

    0 讨论(0)
  • 2020-12-20 08:43

    As I commented, you can treat each number as a binary string of length 32.

    Just multiply these numbers using school arithmetic. You will get a 64 character long string.

    Then just partition it.

    If you want fast multiplication, then you can look into Karatsuba multiplication algorithm.

    0 讨论(0)
  • 2020-12-20 08:46

    If the unsigned long type are supported, this should work:

    void umult32(uint32 a, uint32 b, uint32* c, uint32* d)
    {
      unsigned long long x = ((unsigned long long)a)* ((unsigned long long)b); //Thanks to @Толя
      *c = x&0xffffffff;
      *d = (x >> 32) & 0xffffffff;
    }
    

    Logic borrowed from here.

    0 讨论(0)
提交回复
热议问题