4

What is time-complexity of math.sqrt implementation in Java ? Java has time-complexity implemented in some technique whose, time-complexity I am trying to determine.

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

2 Answers2

3

In most cases, Java attempts to use the "smart-power" algorithm, which results in a time-complexity of O(log n). Smart power Algorithm

Also, it appears that in different cases, you could end up with different complexities; Why is multiplied many times faster than taking the square root?

Community
  • 1
  • 1
Evan Bechtol
  • 2,855
  • 2
  • 18
  • 36
  • 1
    from the [source code](https://developer.classpath.org/doc/java/lang/StrictMath-source.html), Math.sqrt will use bit operation trick and directly determine every bit in sqrt(n), which is at most O(64) ~ O(1) – maplemaple Jun 19 '21 at 19:18
2

It looks like it is implemented by delegating to the sqrt method StrictMath which is a native method.

Thus it seems the answer would be implementation specific.

Strictly speaking it is O(1). In theory (but obviously not practice), we could iterate over all doubles and find the maximum time.

In addition, the time complexity of Math.sqrt(n) does not directly depend on n but instead on the amount of space needed to represent n which for doubles should be constant.

emory
  • 10,725
  • 2
  • 30
  • 58