My code for large integer sqrt
<?php
$y2 = gmp_init('28626386478758000000000000909090904'); // Example GMP number
$sqrt = gmp_sqrt($y2);
echo "Square root is: " . gmp_strval($sqrt) . "n"; // Output the square root
?>
It gives result
Square root is: 169193340527214604
But how to get decimal part of sqrt?
2
Answers
In PHP, when using the
gmp_sqrt()
function, you’ll only get the integer part of the square root. If you’re looking to calculate the decimal portion as well, you’ll need to use thebcmath
extension, which can handle arbitrary precision numbers.Here’s a quick way to get that decimal part using a custom function. This method will give you a square root with a certain number of decimal places:
What’s happening here:
We start by guessing the square root (half the value) and keep refining that guess.
The loop continues until the new guess is very close to the previous one, with the number of decimal places controlled by the $precision argument.
bcadd(), bcdiv(), and bccomp() are used for calculations with large numbers.
You can tweak the precision to get as many decimal places as you need, making this method useful when working with really large numbers like in your case.
This approach gives you the desired square root, including the decimal portion, for large numbers in PHP!
To compute the square root of an arbitrarily large number, you can use the
bcsqrt()
function of the BCMath extension:Output: