Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Squaring n-bit int vs. multiplying two n-bit ints

Tags:

algorithm

Disclaimer: Homework question. I'm looking for a hint…

Professor F. Lake tells his class that it is asymptotically faster to square an n-bit integer than to multiply two n-bit integers. Should they believe him?

I believe that multiplying two n-bit ints via shift/add is an O(n) operation, but I can't see why squaring an n-bit int would be any different. Am I missing something?

like image 455
Student Avatar asked Sep 29 '10 00:09

Student


People also ask

Is squaring faster than multiplying?

2.1. Squaring is used to substitute for multiplication because squaring is much more efficient than multiplication [7], [8], [9], [10], [11].

When multiplying two n-bit numbers What is the size of the result?

In general, an N × N multiplier multiplies two N-bit numbers and produces a 2N-bit result. The partial products in binary multiplication are either the multiplicand or all 0's.

How many bits do we get if we multiply two 4 bit numbers?

The final multiplication result will be available in the A and Q registers as 10001111 as shown in the figure. A 4 × 4 unsigned binary multiplier takes two, four bit inputs and produces an output of 8 bits. Similarly 8 × 8 multiplier accepts two 8 bit inputs and generates an output of 16 bits.

What is the time complexity of multiplying two numbers?

Hence, we know that multiplication has a time complexity of O(N logN) while usual algorithms in practice have a time complexity of O(N^2).


2 Answers

Since you wanted only a hint, answer comes from this equation: (a + b)^2 = a^2 + b^2 + 2*a*b

To not spoil the puzzle, I've posted complete solution separately :)

like image 55
Nikita Rybak Avatar answered Oct 19 '22 23:10

Nikita Rybak


Imagine that squaring is actually asymptotically faster. Then if you have a * b, you could calculate:

a = m + n
b = m - n

Then solving this equation system gives:

m = (a+b)/2
n = (a-b)/2

But then we have

a * b = (m+n)*(m-n) = m² - n²

or without intermediate variables:

a * b = ((a+b)² - (a-b)²)/4

So you can replace any multiplication by two squaring operations (and some additions and division by 4, which is just a bit shift, and these can be all ignored for asymptotical complexity). So the complexity of multiplication is at most twice the complexity of squaring. Of course, "twice" is a constant factor, which means both have the same asymptotical complexity.

like image 11
Landei Avatar answered Oct 19 '22 23:10

Landei