What is gmp_sqrt in PHP?

The gmp_sqrt() is a function in PHP that calculates the square root of a GMP number.

Syntax

gmp_sqrt(GMP|int|string $num): GMP

Parameters

The function takes in one parameter, num.

num can be a numeric string, GMPGNU Multiple Precision Arithmetic Library object, or of type int.

Return value

The function returns the integer part of the square root. The value returned is a GMP type number.

Code

Let’s run the following code to calculate the square root of a GMP number using gmp_sqrt() function.

<?php
//numeric string as argument
$type1 = "9";
$squareRoot = gmp_sqrt($type1);
echo $squareRoot."\n";
//GMP number as argument
//gmp_init is used to create a GMP number
$type2 = gmp_init(7, 10);
$squareRoot = gmp_sqrt($type2);
echo $squareRoot."\n";
?>
  • Line 3: Initializes the variable $type1.

  • Line 4: Attempts to calculate the square root of $type1 using the gmp_sqrt() function.

  • Line 9: Initializes the variable $type2 using gmp_init(), creating a GMP number. The function gmp_init(7, 10) initializes a GMP number with the value 7 using base 10.

  • Line 10: Computes the square root of the GMP number $type2 using gmp_sqrt().

Free Resources