What is Integer.sqrt() in Ruby?

In Ruby 2.5.0, the Integer.sqrt() function returns the integer square root of a non-negative integer. This function returns the largest positive integer which is less than or equal to the square root of that number.

Figure 1 shows the mathematical representation of the Integer.sqrt() function.

Figure 1: Mathematical representation of the Integer.sqrt() function

Syntax

Integer.sqrt(number)

Parameter

Integer.sqrt() requires a non-negative number as a parameter. Otherwise, a DomainError occurs.

Return value

Integer.sqrt() returns the integer square root of the number sent as a parameter.

This is almost equivalent to:

Math.sqrt(n).floor()

Example

#example
#integer square root
print "sqrt(4):", Integer.sqrt(4), "\n"
# output = 2
print "sqrt(5):", Integer.sqrt(5), "\n"
# output = 2
print "sqrt(6):", Integer.sqrt(6), "\n"
# output = 2

Output

sqrt(4):2
sqrt(5):2
sqrt(6):2

Free Resources