Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : GMP Functions

GMP Functions


These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.


Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.


If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.


This extension is available on Windows platforms since PHP 5.1.0.


You can download the GMP library from » This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.


In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

Most GPM functions operate on or return GMP number resources.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

GMP_ROUND_ZERO (integer)
GMP_VERSION (string)
The GMP library version


Example 779. Factorial function using GMP

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

gmp_strval(fact(1000)) . "\n";

This will calculate factorial of 1000 (pretty big number) very fast.

See Also

More mathematical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.

Table of Contents

gmp_abs — Absolute value
gmp_add — Add numbers
gmp_and — Logical AND
gmp_clrbit — Clear bit
gmp_cmp — Compare numbers
gmp_com — Calculates one's complement
gmp_div_q — Divide numbers
gmp_div_qr — Divide numbers and get quotient and remainder
gmp_div_r — Remainder of the division of numbers
gmp_div — Alias of gmp_div_q()
gmp_divexact — Exact division of numbers
gmp_fact — Factorial
gmp_gcd — Calculate GCD
gmp_gcdext — Calculate GCD and multipliers
gmp_hamdist — Hamming distance
gmp_init — Create GMP number
gmp_intval — Convert GMP number to integer
gmp_invert — Inverse by modulo
gmp_jacobi — Jacobi symbol
gmp_legendre — Legendre symbol
gmp_mod — Modulo operation
gmp_mul — Multiply numbers
gmp_neg — Negate number
gmp_nextprime — Find next prime number
gmp_or — Logical OR
gmp_perfect_square — Perfect square check
gmp_popcount — Population count
gmp_pow — Raise number into power
gmp_powm — Raise number into power with modulo
gmp_prob_prime — Check if number is "probably prime"
gmp_random — Random number
gmp_scan0 — Scan for 0
gmp_scan1 — Scan for 1
gmp_setbit — Set bit
gmp_sign — Sign of number
gmp_sqrt — Calculate square root
gmp_sqrtrem — Square root with remainder
gmp_strval — Convert GMP number to string
gmp_sub — Subtract numbers
gmp_testbit — Tests if a bit is set
gmp_xor — Logical XOR

Code Examples / Notes » ref.gmp


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:
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.

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.
 function isBitSet($bitMask, $bitMap)
   return (bool) gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));


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){
return floatval(gmp_strval($d));
function f_or($a,$b){
return floatval(gmp_strval($d));
function f_xor($a,$b){
return floatval(gmp_strval($d));
function f_not($a){
return floatval(gmp_strval($d,10));
function f_dec2bin($a){
return gmp_strval($a,2);
function f_bin2dec($a){
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){
   $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);
function f_dec2cidr($a){
return $d;
function f_dec2ipall($dNet,$dMask){
 if($IpAll["nIp"] > 2){
 return $IpAll;
GMP install steps in Mandrake 9.1:
cp -r /usr/src/php-devel/extensions/gmp /tmp/gmp
cd /tmp/gmp
make install
echo "extension =" > /etc/php/90_gmp.ini
Restart apache web server.
---------------------------------------------------------- is in:
look in phpinfo, the string:
Needs these tools:
all rpm´s that are envolved to run and compile gmp (*gmp*.rpm)
Some docs about self contained extensions:

Change Language

Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Haru PDF Functions
hash Functions
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker