Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
class method
Integer.sqrt
(::int n) -> ::Integer
Integer.sqrt(numeric) → integer
numeric.c
View on GitHub ↗
static VALUE
rb_int_s_isqrt(VALUE self, VALUE num)
{
unsigned long n, sq;
num = rb_to_int(num);
if (FIXNUM_P(num)) {
if (FIXNUM_NEGATIVE_P(num)) {
domain_error("isqrt");
}
n = FIX2ULONG(num);
sq = rb_ulong_isqrt(n);
return LONG2FIX(sq);
}
else {
size_t biglen;
if (RBIGNUM_NEGATIVE_P(num)) {
domain_error("isqrt");
}
biglen = BIGNUM_LEN(num);
if (biglen == 0) return INT2FIX(0);
#if SIZEOF_BDIGIT <= SIZEOF_LONG
/* short-circuit */
if (biglen == 1) {
n = BIGNUM_DIGITS(num)[0];
sq = rb_ulong_isqrt(n);
return ULONG2NUM(sq);
}
#endif
return rb_big_isqrt(num);
}
}
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.