How to work with big numbers in PHP?

2020-02-11 04:49发布

问题:

How to work with big numbers in PHP?

such as

(6*27^0+17*27^1+11*27^2+18*27^3+25*27^4+4*27^5)^65537

回答1:

You can go for BCMath to work with big numbers.



回答2:

GMP's actually faster than BCMath for bigintegers if you have it installed. If you have neither BCMath or GMP installed you can use phpseclib's pure-php biginteger implementation.

That implementation uses GMP or BCmath if they're available, in that order, and it's own internal implementation otherwise.



回答3:

There are many options:

  • The GMP extension
  • The BCMath Extension
  • Litipk PHP BigNumbers ( https://github.com/litipk/php-bignumbers )
  • Flourish Numbers ( http://flourishlib.com/docs/fNumber )


回答4:

Given the question title, I'm assuming that the OP meant ^ as a power operator and not PHP's XOR operator, although the actual numbers make me doubt.

This can be achieved using the Brick\Math library (disclaimer: I authored it):

use Brick\Math\BigInteger;

// Not using BigInteger just yet as the numbers are small, although we could
$value =  6 * 27 ** 0
       + 17 * 27 ** 1
       + 11 * 27 ** 2
       + 18 * 27 ** 3
       + 25 * 27 ** 4
       +  4 * 27 ** 5;

echo BigInteger::of($value)->power(65537); // 529970661615774734826076722083948398443...

I'm sparing you the rest of the 514566 digits :)