Why is squaring a number faster than multiplying two random numbers?

前端 未结 14 2063
终归单人心
终归单人心 2021-01-30 07:18

Multiplying two binary numbers takes n^2 time, yet squaring a number can be done more efficiently somehow. (with n being the number of bits) How could that be?

Or is i

14条回答
  •  一生所求
    2021-01-30 07:46

    First of all great question! I wish there were more questions like this.

    So it turns out that the method I came up with is O(n log n) for general multiplication in the arithmetic complexity only. You can represent any number X as

    X = x_{n-1} 2^{n-1} + ... + x_1 2^1 + x_0 2^0
    Y = y_{m-1} 2^{m-1} + ... + y_1 2^1 + y_0 2^0
    

    where

    x_i, y_i \in {0,1}
    

    then

    XY = sum _ {k=0} ^ m+n r_k 2^k
    

    where

    r_k = sum _ {i=0} ^ k x_i y_{k-i}
    

    which is just a straight forward application of FFT to find the values of r_k for each k in (n +m) log( n + m) time.

    Then for each r_k you must determine how big the overflow is and add it up accordingly. For squaring a number this means O(n log n) arithmetic operations.

    You can add up the r_k values more efficiently using the Schönhage–Strassen algorithm to obtain a O(n log n log log n) bit operation bound.

    The exact answer to your question is already posted by Eric Bainville.

    However, you can get a much better bound than O(n^2) for squaring a number simply because there exist much better bounds for multiplying integers!

提交回复
热议问题