Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Integer.sqrt

Integer.sqrt(n) → integer

Returns the integer square root of the non-negative integer n, i.e. the largest non-negative integer less than or equal to the square root of n.

Example
Integer.sqrt(0)        #=> 0
Integer.sqrt(1)        #=> 1
Integer.sqrt(24)       #=> 4
Integer.sqrt(25)       #=> 5
Integer.sqrt(10**400)  #=> 10**200

Equivalent to Math.sqrt(n).floor, except that the result of the latter code may differ from the true value due to the limited precision of floating point arithmetic.

Example
Integer.sqrt(10**46)     #=> 100000000000000000000000
Math.sqrt(10**46).floor  #=>  99999999999999991611392 (!)

If n is not an Integer, it is converted to an Integer first. If n is negative, a Math::DomainError is raised.

See also .from_prime_division #% .each_prime #& also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1