Skip to content

Core\BigInt::sqrt

$bigInt->sqrt(): Core\BigInt

Returns the integer square root of this number, as a new Core\BigInt.

The square root of a whole number is usually not a whole number itself. sqrt returns the largest whole number whose square is not larger than this one. The square root of 8 is between 2 and 3, so sqrt returns 2. What comes after the decimal point is dropped, and the result is never rounded up.

A negative number has no integer square root. sqrt throws an ArithmeticError when you call it on one, so check the sign first where a number may be negative.

Good to know: the result is exact at every size. Multiply it by itself and compare that with the number you started from, and you know whether that number is a perfect square.

Return value

Returns Core\BigInt. A BigInt: the square root, rounded down. For 8, the result is 2.

Errors

  • ArithmeticErrorThis value is negative. A negative number has no integer square root.

Examples

The square root of a number

<?nvs
// Shows the square root of a whole number, and what you get when the root is
// not a whole number itself.
// 9 is 3 times 3, so this prints 3.
echo Core\BigInt::of(9)->sqrt(), "\n";
// The square root of 8 is between 2 and 3. `sqrt` returns the largest whole
// number whose square is not larger than 8, so this prints 2.
echo Core\BigInt::of(8)->sqrt(), "\n";
// The result is never rounded up. 15 is one short of 16, and this prints 3.
echo Core\BigInt::of(15)->sqrt(), "\n";
// The square root of 0 is 0.
echo Core\BigInt::of(0)->sqrt(), "\n";
Output
3
2
3
0

When the number is negative

<?nvs
// Shows what `sqrt` does with a negative number. No whole number gives a
// negative number when it is multiplied by itself.
var $value = Core\BigInt::of(-9);
// `sqrt` throws an `ArithmeticError`, and the message names the method that
// refused.
try {
echo $value->sqrt(), "\n";
} catch (ArithmeticError $negative) {
echo $negative->message, "\n";
}
// Test the sign first where a number may be negative. `abs` removes the minus
// sign, so this prints 3.
if ($value->sign() < 0) {
echo $value->abs()->sqrt(), "\n";
}
Output
Core\BigInt::sqrt(): a negative value has no integer square root
3

Checking a number is a perfect square

<?nvs
// Shows how to test that a number is a perfect square. A program does this
// before it lays a set of items out in a square grid. The counts are too large
// for an `int`, so they arrive as text.
array<string> $counts = ['100000000000000000000000000000000000000', '12345678901234567890'];
var $root = Core\BigInt::of(0);
foreach ($counts as string $count) {
var $value = Core\BigInt::parse($count);
$root = $value->sqrt();
// A number is a perfect square when its root multiplied by itself gives
// that number back. This prints "square" and then "not square".
echo $root->multipliedBy($root)->compareTo($value) == 0 ? "square\n" : "not square\n";
}
Output
square
not square