Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a BigInteger class in PHP?

Tags:

php

biginteger

Is there a BigInteger class in PHP? If so, how do I access it or use it?

like image 727
freddiefujiwara Avatar asked Dec 13 '10 08:12

freddiefujiwara


People also ask

Is BigInteger a wrapper class?

BigInteger. This version of BigInteger is just a wrapper class for long and its purpose is to only to support a JDK 1.0. 2 version of BigDecimal.

What is the difference between integer and BigInteger?

Remarks. The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.

How do you use the BigInteger operator?

You can not use the operators on BigInteger . They are not primitives like int , they are classes. Java has no operator overloading.


2 Answers

Hopefully helpfull links :

  • http://php.net/manual/en/ref.bc.php
  • http://php.net/manual/en/ref.gmp.php

EDIT: Math_BigInteger

Example from http://phpseclib.sourceforge.net/documentation/math.html :

Implements an arbitrary precision integer arithmetic library. Uses gmp or bcmath, if available, and an internal implementation, otherwise.

<?php
    include('Math/BigInteger.php');

    $a = new Math_BigInteger(2);
    $b = new Math_BigInteger(3);

    $c = $a->add($b);

    echo $c->toString(); // outputs 5
?>
like image 199
Thariama Avatar answered Oct 08 '22 14:10

Thariama


Even though this question is old, it comes up as first result when Googling for BigInteger PHP, so for anyone interested, I open-sourced a library called Brick\Math offering BigInteger, BigDecimal and BigRational classes.


Usage

use Brick\Math\BigInteger;
use Brick\Math\RoundingMode;

Addition:

echo BigInteger::of('9999999999999999999999999')->plus(1);
// 10000000000000000000000000

Subtraction:

echo BigInteger::of('10000000000000000000000000')->minus(1);
// 9999999999999999999999999

Multiplication:

echo BigInteger::of('3333333333333333333333333')->multipliedBy(11);
// 36666666666666666666666663

Division:

echo BigInteger::of('1000000000000000000000')->dividedBy(3, RoundingMode::UP);
// 333333333333333333334

Exponentiation:

echo BigInteger::of(11)->power(50);
// 11739085287969531650666649599035831993898213898723001

You can easily chain method calls:

echo BigInteger::of(3)->multipliedBy(7)->minus(1)->dividedBy(10);

Installation

Just install with Composer and you're done:

composer require brick/math

The library automatically uses the GMP and BCMath extensions when available, to speed up calculations, but will also work without them thanks to a pure PHP implementation.

like image 43
BenMorel Avatar answered Oct 08 '22 15:10

BenMorel