Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

Integer.sqrt

(::int n) -> ::Integer
Integer.sqrt(numeric) → integer

Returns the integer square root of the non-negative integer n, which is the largest non-negative integer less than or equal to the square root of numeric.

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

If numeric is not an Integer, it is converted to an Integer:

Example
Integer.sqrt(Complex(4, 0))  # => 2
Integer.sqrt(Rational(4, 1)) # => 2
Integer.sqrt(4.0)            # => 2
Integer.sqrt(3.14159)        # => 1

This method is equivalent to Math.sqrt(numeric).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

Raises an exception if numeric is negative.

See also .try_convert #% also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0