Hacker News new | ask | show | jobs
by hansvm 1829 days ago
> What kind of savage wants the square root of an integer?

It comes up moderately frequently (e.g., in prime sieves). It's usually defined as the largest integer X whose square X^2 is no greater than N. Search any sufficiently large codebase (postgres or something) and you'll probably find one or more functions called something like "isqrt".

My favorite implementation just takes Newton's method and blindly applies it to integers. It happens to converge for at least one starting value.

1 comments

good point! but notice that this is an entirely different function than flotaing-point sqrt; and it has, appropriately, a different name.
The integer square root is mild a generalization of the floating point square root (in the sense that if you swap ints for floats you get the ordinary sqrt back out). With that in mind, do you think that the different name is chosen because it's a fundamentally different operation or just because of limitations in the dispatch mechanisms of common languages?
it would be very confusing to have both functions go by the same name. Very often you want the floating-point valued square root of an integer. Having the two functions with different names is much clearer, and better than forcing a conversion just to dispatch another function that performs a different computation.