3

Stumbled across a (terrible) algorithm for computing the square root of a number. Got into a small argument about the time complexity. I assert that the time complexity is O(n^2) because for n input, it will be multiplied n times. My friend asserts that the time complexity is actually O(n). Who is right and why?

def squareRoot(x):
if x<0:
    return "undefined"
elif x==0:
    return 0
for i in range(0,x):
    if(i*i)==x:
        return i
Sandeep
  • 1,504
  • 7
  • 22
  • 32
hrazzer
  • 79
  • 8

3 Answers3

1

It's O(n), because, in the worst case, you perform x multiplications and tests, so your computation time grows linear with your input.

Turbofant
  • 517
  • 11
  • 24
0

First we need to know what the complexity of integer multiplication is.

For simplicity, we'll use the Schönhage–Strassen algorithm . The complexity is O(n log n log log n) for numbers with n digits.

Of course the number n actually has O(log n) digits, so to multiply numbers of value n, the time complexity is O(log n log log n log log log n)

There are n numbers of up to n size to multiply, so overall it is O(n log n log log n log log log n)

Thus O(n^2) was more correct, in the same way that O(n!) was correct. Correct but unhelpful. And O(n) is simply wrong, without several assumptions that were not made.

Do note that you can do better with better multiplication algorithms.

moreON
  • 1,977
  • 17
  • 19
  • Why you need to be this complex. Who said we are talking about large numbers? Anice build-up though :) – vish4071 Apr 20 '16 at 12:10
  • Who made any assumption about the size of the numbers at all? Nothing in the question restricted their size, so we have to go with the most general possible case. – moreON Apr 21 '16 at 00:14
0

Lets us first see how this algo works.

In worst case, that is, x is not perfect square, and x is prime, the time complexity will be O(n).
In best case. that is the no. is perfect square, then it will be in order of SQRT(n).

Jahangir Ali
  • 55
  • 1
  • 14