downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

gmp_abs> <textdomain
[edit] Last updated: Mon, 01 Nov 2010

view this page in

XLVI. Funciones GMP

Introducción

Estas funciones permiten trabajar con números enteros de cualquier longitud arbitraria empleando la librerí GNUMP.

Estas funciones se añadieron en la versión de PHP 4.0.4.

Nota: La mayoría de funciones GMP aceptan como argumentos números GMP, definidos como resource más adelante. Sin embargo, la mayoría de estas funciones también aceptan argumentos de tipo numérico o cadenas de texto, ya que se pueden convertir fácilmente. Además, si existe una función más rápida que pueda operar con enteros, se empleará esa función en lugar de la otra función más lenta. Este proceso se realiza de forma automática y transparente, por lo que a modo de resumen se puede decir que se pueden emplear números de tipo entero en todas aquellas funciones cuyos parámetros se han definido como números GMP. Vea también la documentación de la función gmp_init().

Aviso

Si se quiere indicar de forma explícita un número entero muy grande, se recomienda hacerlo en forma de cadena. De otra forma, PHP lo interpreta como un entero y podría producirse una pérdida de precisión antes de comenzar a utilizar las funciones GMP.

Nota: Esta extensión está disponible en sistemas Windows desde la versión de PHP 5.1.0.

Requisitos

La librería GMP de puede descargar desde la dirección http://www.swox.com/gmp/. Además, en ese sitio web también está disponible el manual de GMP.

Para poder utilizar estas funciones se requiere al menos la versión 2 de GMP. Algunas funciones pueden requerir además alguna versión más reciente.

Instalación

Para poder utilizar estas funciones, se debe compilar PHP con soporte de GMP mediante la opción --with-gmp.

Configuración en tiempo de ejecución

Esta extensión no tiene directivas de configuración en php.ini.

Tipos de recursos

Esta extensión no tiene ningún tipo de recurso definido.

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)

Ejemplos

Ejemplo 1. Cálculo del factorial usando GMP

<?php
function fact($x)
{
   
$factorial = 1;
    for (
$i=2; $i < $x; $i++) {
       
$factorial = gmp_mul($factorial, $i);
    }
    return
$factorial;
}

echo
gmp_strval(fact(1000)) . "\n";
?>

En el ejemplo se calcula el factorial de número 1000 (un número bastante grande para calcular su factorial) de forma bastante rápida.

Ver también

Se pueden encontrar muchas otras funciones matemáticas en las secciones Funciones matemáticas de precisión arbitraria BCMath y Funciones Matemáticas.

Tabla de contenidos
gmp_abs -- Valor absoluto
gmp_add -- Suma números
gmp_and -- Realiza una operación de AND lógico
gmp_clrbit -- Borra un bit
gmp_cmp -- Compara números
gmp_com -- Calcula el complementario
gmp_div_q -- Divide números
gmp_div_qr -- Divide números y obtiene el cociente y el resto
gmp_div_r -- Resto de la división de números
gmp_div -- Alias of gmp_div_q()
gmp_divexact -- División exacta de números
gmp_fact -- Factorial
gmp_gcd -- Calcula el MCD (máximo común divisor)
gmp_gcdext -- Calcula el MCD y los coeficientes
gmp_hamdist -- Distancia de Hamming
gmp_init -- Crea un número GMP
gmp_intval -- Convierte números GMP a números enteros
gmp_invert -- Invierte según el módulo
gmp_jacobi -- Calcula el símbolo de Jacobi
gmp_legendre -- Calcula el símbolo de Legendre
gmp_mod -- Operación Módulo
gmp_mul -- Multiplica números
gmp_neg -- Cambia el signo de un número
gmp_or -- Realiza una operación de OR lógico
gmp_perfect_square -- Comprueba si es un cuadrado perfecto
gmp_popcount -- Calcula la población de un número
gmp_pow -- Eleva un número a una potencia
gmp_powm -- Eleva un número a una potencia según el módulo
gmp_prob_prime -- Comprueba si un número tiene probabilidades de ser un número primo
gmp_random -- Genera un número aleatorio
gmp_scan0 -- Busca un 0
gmp_scan1 -- Busca un 1
gmp_setbit -- Establece el valor de un bit
gmp_sign -- Obtiene el signo del número
gmp_sqrt -- Calcula la raíz cuadrada
gmp_sqrtrem --  Calcula la raíz cuadrada con el resto
gmp_strval -- Convierte un número GMP a una cadena de texto
gmp_sub -- Resta números
gmp_xor -- Realiza una operación de XOR lógico


gmp_abs> <textdomain
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Funciones GMP
Nitrogen 06-Sep-2010 08:02
I made a function that can be used for converting numbers to any base you wish.. instead of returning a string of pre-defined index of characters (i.e. 0-9a-z) you could simply make your own of any length using the array of indexes it returns.
I looked around and didn't see anybody made one, I needed one for a simple compression algorithm with only numbers, I've not actually made it yet but this was an initial idea.

<?php
// ConvertBase function explained:
// we add an array item $Input%$Base floored and divide $Input by $Base floored.
// repeat until $Input is no longer above 0.

function ConvertBase($Input,$Base=10) {
 
$Input=gmp_init($Input);
 
$Result=array();

  for(
$i=0;$i<1||gmp_sign($Input)==1;$i++) {
   
$Result[]=gmp_intval(gmp_mod($Input,$Base));
   
$Input=gmp_div_q($Input,$Base);
  }
 
$Result=array_reverse($Result);
  return(
$Result);
}

// an example how gmp_strval($.., 36); could be achieved:

// the funny emergency number from The IT Crowd
// (leading zeroes aren't liked in gmp_init though)
$Input = '1189998819991197253';

// our example 36 characters used in gmp_strval($.., 36);
$Chars = '0123456789abcdefghijklmnopqrstuvwxyz';

// count the $Chars so they're all used
// or use your own number less than the length of $Chars
$Base = strlen($Chars);

// perform
$Result = ConvertBase($Input,$Base);

// replace the resulting index with the corrosponding characters of the index in $Chars
for($i=0;$i<count($Result);$i++)
 
$Result[$i]=$Chars{$Result[$i]};

// compare
printf("gmp_strval:  %s\r\n",gmp_strval($Input,36));
printf("BaseConvert: %s\r\n",implode($Result));

/* OUTPUT:
gmp_strval:  91h7dixfq6h1
BaseConvert: 91h7dixfq6h1
*/
?>
The example shows a familiar result of course, but the idea of this function was so that you can use whatever base you wish, and display entirely your own output to represent any number of choice.

Also, for those who wish to do bitwise shifting, it's quite simple.. to shift left, just multiply the number by pow(2,x), and to shift right, divide by pow(2,x).

<?php
function gmp_shiftl($x,$n) { // shift left
 
return(gmp_mul($x,gmp_pow(2,$n)));
}

function
gmp_shiftr($x,$n) { // shift right
 
return(gmp_div($x,gmp_pow(2,$n)));
}
?>

Have fun,
Nitrogen.
john at worldmapad dot com 22-Jul-2006 11:24
Here's a quick and dirty way to use simple GMP functions with PHP without recompiling. It is dependent upon the use of the exec() function, so make sure you can use exec(). While in safe mode you must consider the safe_mode_exec_dir directive. And don't simply pass user input to the exec function without validating the input first!

Download and Install GMP as instructed in README and INSTALL files.
On my MAC OS X Server, I just did the following:
./configure
make
make check
make install
This installed it in the /usr/local directory. There were some errors, but not with any functions I needed.
Within the gmp-4.#.# cd into the demos directory. Then compile pexpr.c by typing:
make pexpr
This is a simple expressions parser which serves as a simple interface to some of the basic GMP functions.
You can test it then like:
./pexpr "102394874783 * 23498748";
Now you may interface with it using PHP's exec() function.
richard-slater.co.uk 22-Feb-2004 01:03
For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

<?php
 
function isBitSet($bitMask, $bitMap)
  {
    return (bool)
gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));
  }
?>
helvecio_oliveira at yahoo dot com dot br 15-Oct-2003 01:51
=============================================================
A set of very nice functions to handle IP Address with gmplib:

The best way to store a range into a database is store:
dNet ..... decimal representation of a Net
dMask .... decimal representation of a Mask

All another parameters can be calculated.

<?
/*
f_ip2dec($a) ................... IP string to decimal
f_dec2ip($a) ................... decimal to IP string

f_dec2ipall($dNet,$dMask) ...... decimal Net and Mask to an Array with several IP parameters

f_dec2cidr($a) ................. decimal Mask to CIDR

f_and($a,$b) ................... and
f_or($a,$b) .................... or
f_xor($a,$b) ................... xor
f_not($a) ...................... not
f_dec2bin($a) .................. decimal to binary string
f_bin2dec($a) .................. binary string to decimal
*/

function f_and($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_and($a,$b);
return
floatval(gmp_strval($d));
}

function
f_or($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_or($a,$b);
return
floatval(gmp_strval($d));
}

function
f_xor($a,$b){
$a=gmp_init(strval($a));
$b=gmp_init(strval($b));
$d=gmp_xor($a,$b);
return
floatval(gmp_strval($d));
}

function
f_not($a){
$a=gmp_init(strval($a));
$d=gmp_strval($a,2);
$d=str_replace("1","x",$d);
$d=str_replace("0","1",$d);
$d=str_replace("x","0",$d);
$d=gmp_init($d,2);
return
floatval(gmp_strval($d,10));
}

function
f_dec2bin($a){
$a=gmp_init(strval($a));
return
gmp_strval($a,2);
}

function
f_bin2dec($a){
$a=gmp_init(strval($a),2);
return
floatval(gmp_strval($a,10));
}

function
f_ip2dec($a){
$d = 0.0;
$b = explode(".", $a,4);
for (
$i = 0; $i < 4; $i++) {
       
$d *= 256.0;
       
$d += $b[$i];
    };
return
$d;
}

function
f_dec2ip($a){
   
$b=array(0,0,0,0);
   
$c = 16777216.0;
   
$a += 0.0;
    for (
$i = 0; $i < 4; $i++) {
       
$k = (int) ($a / $c);
       
$a -= $c * $k;
       
$b[$i]= $k;
       
$c /=256.0;
    };
   
$d=join('.', $b);
    return(
$d);
}

function
f_dec2cidr($a){
$a=gmp_init(strval($a));
$d=strlen(str_replace("0","",gmp_strval($a,2)));
return
$d;
}

function
f_dec2ipall($dNet,$dMask){
 
$dWildCard=f_not($dMask);
 
$IpAll["Net"]=f_dec2ip($dNet);
 
$IpAll["Mask"]=f_dec2ip($dMask);
 
$IpAll["WildCard"]=f_dec2ip($dWildCard);
 
$IpAll["Cidr"]=f_dec2cidr($dMask);
 
$IpAll["Bcast"]=f_dec2ip(f_or($dNet,$dWildCard));
 
$IpAll["nIp"]=$dWildCard+1;
 
$IpAll["nIpUtil"]=$dWildCard-1;
  if(
$IpAll["nIp"] > 2){
       
$IpAll["IpFrom"]=f_dec2ip($dNet+1);
       
$IpAll["IpTo"]=f_dec2ip($dNet+$dWildCard-1);
  }
  else
  {
       
$IpAll["IpFrom"]="-";
       
$IpAll["IpTo"]="-";
       
$IpAll["nIpUtil"]=0;
  }
  return
$IpAll;
}

?>

=============================================================
GMP install steps in Mandrake 9.1:
----------------------------------------------------------
cp -r /usr/src/php-devel/extensions/gmp /tmp/gmp
cd /tmp/gmp
phpize
./configure
make install
echo "extension = gmp.so" > /etc/php/90_gmp.ini

Restart apache web server.
----------------------------------------------------------
gmp.so is in:
/usr/lib/php/extensions/

look in phpinfo, the string:
/etc/php/90_gmp.ini

Needs these tools:
autoconf
automake
libtool
m4
php430-devel-430-11mdk.rpm
all rpm´s that are envolved to run and compile gmp (*gmp*.rpm)

Some docs about self contained extensions:
/usr/share/doc/php430-devel-430/SELF-CONTAINED-EXTENSIONS
=============================================================

 
show source | credits | sitemap | contact | advertising | mirror sites