APIdock / Ruby
/
method

sqrt

ruby latest stable - Class: Integer
sqrt(p1)
public

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.

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.

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.

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);
 }
}

AltStyle によって変換されたページ (->オリジナル) /