PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/phpseclib/Math/BigInteger.php

http://github.com/fuel/core
PHP | 1959 lines | 968 code | 249 blank | 742 comment | 168 complexity | c5dbeaf6cb2e8d519257746b40f46c96 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. namespace PHPSecLib;
  4. /**
  5. * Pure-PHP arbitrary precision integer arithmetic library.
  6. *
  7. * Supports base-2, base-10, base-16, and base-256 numbers. Uses the GMP or BCMath extensions, if available,
  8. * and an internal implementation, otherwise.
  9. *
  10. * PHP versions 4 and 5
  11. *
  12. * {@internal (all DocBlock comments regarding implementation - such as the one that follows - refer to the
  13. * {@link MATH_BIGINTEGER_MODE_INTERNAL MATH_BIGINTEGER_MODE_INTERNAL} mode)
  14. *
  15. * Math_BigInteger uses base-2**26 to perform operations such as multiplication and division and
  16. * base-2**52 (ie. two base 2**26 digits) to perform addition and subtraction. Because the largest possible
  17. * value when multiplying two base-2**26 numbers together is a base-2**52 number, double precision floating
  18. * point numbers - numbers that should be supported on most hardware and whose significand is 53 bits - are
  19. * used. As a consequence, bitwise operators such as >> and << cannot be used, nor can the modulo operator %,
  20. * which only supports integers. Although this fact will slow this library down, the fact that such a high
  21. * base is being used should more than compensate.
  22. *
  23. * When PHP version 6 is officially released, we'll be able to use 64-bit integers. This should, once again,
  24. * allow bitwise operators, and will increase the maximum possible base to 2**31 (or 2**62 for addition /
  25. * subtraction).
  26. *
  27. * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie.
  28. * (new Math_BigInteger(pow(2, 26)))->value = array(0, 1)
  29. *
  30. * Useful resources are as follows:
  31. *
  32. * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)}
  33. * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)}
  34. * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip
  35. *
  36. * Here's an example of how to use this library:
  37. * <code>
  38. * <?php
  39. * include('Math/BigInteger.php');
  40. *
  41. * $a = new Math_BigInteger(2);
  42. * $b = new Math_BigInteger(3);
  43. *
  44. * $c = $a->add($b);
  45. *
  46. * echo $c->toString(); // outputs 5
  47. * ?>
  48. * </code>
  49. *
  50. * LICENSE: This library is free software; you can redistribute it and/or
  51. * modify it under the terms of the GNU Lesser General Public
  52. * License as published by the Free Software Foundation; either
  53. * version 2.1 of the License, or (at your option) any later version.
  54. *
  55. * This library is distributed in the hope that it will be useful,
  56. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  57. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  58. * Lesser General Public License for more details.
  59. *
  60. * You should have received a copy of the GNU Lesser General Public
  61. * License along with this library; if not, write to the Free Software
  62. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  63. * MA 02111-1307 USA
  64. *
  65. * @category Math
  66. * @package Math_BigInteger
  67. * @author Jim Wigginton <terrafrost@php.net>
  68. * @copyright MMVI Jim Wigginton
  69. * @license http://www.gnu.org/licenses/lgpl.txt
  70. * @version $Id: BigInteger.php,v 1.33 2010/03/22 22:32:03 terrafrost Exp $
  71. * @link http://pear.php.net/package/Math_BigInteger
  72. */
  73. /**#@+
  74. * Reduction constants
  75. *
  76. * @access private
  77. * @see Math_BigInteger::_reduce()
  78. */
  79. /**
  80. * @see Math_BigInteger::_montgomery()
  81. * @see Math_BigInteger::_prepMontgomery()
  82. */
  83. define('MATH_BIGINTEGER_MONTGOMERY', 0);
  84. /**
  85. * @see Math_BigInteger::_barrett()
  86. */
  87. define('MATH_BIGINTEGER_BARRETT', 1);
  88. /**
  89. * @see Math_BigInteger::_mod2()
  90. */
  91. define('MATH_BIGINTEGER_POWEROF2', 2);
  92. /**
  93. * @see Math_BigInteger::_remainder()
  94. */
  95. define('MATH_BIGINTEGER_CLASSIC', 3);
  96. /**
  97. * @see Math_BigInteger::__clone()
  98. */
  99. define('MATH_BIGINTEGER_NONE', 4);
  100. /**#@-*/
  101. /**#@+
  102. * Array constants
  103. *
  104. * Rather than create a thousands and thousands of new Math_BigInteger objects in repeated function calls to add() and
  105. * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them.
  106. *
  107. * @access private
  108. */
  109. /**
  110. * $result[MATH_BIGINTEGER_VALUE] contains the value.
  111. */
  112. define('MATH_BIGINTEGER_VALUE', 0);
  113. /**
  114. * $result[MATH_BIGINTEGER_SIGN] contains the sign.
  115. */
  116. define('MATH_BIGINTEGER_SIGN', 1);
  117. /**#@-*/
  118. /**#@+
  119. * @access private
  120. * @see Math_BigInteger::_montgomery()
  121. * @see Math_BigInteger::_barrett()
  122. */
  123. /**
  124. * Cache constants
  125. *
  126. * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid.
  127. */
  128. define('MATH_BIGINTEGER_VARIABLE', 0);
  129. /**
  130. * $cache[MATH_BIGINTEGER_DATA] contains the cached data.
  131. */
  132. define('MATH_BIGINTEGER_DATA', 1);
  133. /**#@-*/
  134. /**#@+
  135. * Mode constants.
  136. *
  137. * @access private
  138. * @see Math_BigInteger::Math_BigInteger()
  139. */
  140. /**
  141. * To use the pure-PHP implementation
  142. */
  143. define('MATH_BIGINTEGER_MODE_INTERNAL', 1);
  144. /**
  145. * To use the BCMath library
  146. *
  147. * (if enabled; otherwise, the internal implementation will be used)
  148. */
  149. define('MATH_BIGINTEGER_MODE_BCMATH', 2);
  150. /**
  151. * To use the GMP library
  152. *
  153. * (if present; otherwise, either the BCMath or the internal implementation will be used)
  154. */
  155. define('MATH_BIGINTEGER_MODE_GMP', 3);
  156. /**#@-*/
  157. /**
  158. * The largest digit that may be used in addition / subtraction
  159. *
  160. * (we do pow(2, 52) instead of using 4503599627370496, directly, because some PHP installations
  161. * will truncate 4503599627370496)
  162. *
  163. * @access private
  164. */
  165. define('MATH_BIGINTEGER_MAX_DIGIT52', pow(2, 52));
  166. /**
  167. * Karatsuba Cutoff
  168. *
  169. * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication?
  170. *
  171. * @access private
  172. */
  173. define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 25);
  174. /**
  175. * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256
  176. * numbers.
  177. *
  178. * @author Jim Wigginton <terrafrost@php.net>
  179. * @version 1.0.0RC4
  180. * @access public
  181. * @package Math_BigInteger
  182. */
  183. class Math_BigInteger {
  184. /**
  185. * Holds the BigInteger's value.
  186. *
  187. * @var Array
  188. * @access private
  189. */
  190. var $value;
  191. /**
  192. * Holds the BigInteger's magnitude.
  193. *
  194. * @var Boolean
  195. * @access private
  196. */
  197. var $is_negative = false;
  198. /**
  199. * Random number generator function
  200. *
  201. * @see setRandomGenerator()
  202. * @access private
  203. */
  204. var $generator = 'mt_rand';
  205. /**
  206. * Precision
  207. *
  208. * @see setPrecision()
  209. * @access private
  210. */
  211. var $precision = -1;
  212. /**
  213. * Precision Bitmask
  214. *
  215. * @see setPrecision()
  216. * @access private
  217. */
  218. var $bitmask = false;
  219. /**
  220. * Mode independant value used for serialization.
  221. *
  222. * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for
  223. * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value,
  224. * however, $this->hex is only calculated when $this->__sleep() is called.
  225. *
  226. * @see __sleep()
  227. * @see __wakeup()
  228. * @var String
  229. * @access private
  230. */
  231. var $hex;
  232. /**
  233. * Converts base-2, base-10, base-16, and binary strings (eg. base-256) to BigIntegers.
  234. *
  235. * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using
  236. * two's compliment. The sole exception to this is -10, which is treated the same as 10 is.
  237. *
  238. * Here's an example:
  239. * <code>
  240. * <?php
  241. * include('Math/BigInteger.php');
  242. *
  243. * $a = new Math_BigInteger('0x32', 16); // 50 in base-16
  244. *
  245. * echo $a->toString(); // outputs 50
  246. * ?>
  247. * </code>
  248. *
  249. * @param optional $x base-10 number or base-$base number if $base set.
  250. * @param optional integer $base
  251. * @return Math_BigInteger
  252. * @access public
  253. */
  254. function __construct($x = 0, $base = 10)
  255. {
  256. if ( !defined('MATH_BIGINTEGER_MODE') ) {
  257. switch (true) {
  258. case extension_loaded('gmp'):
  259. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP);
  260. break;
  261. case extension_loaded('bcmath'):
  262. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH);
  263. break;
  264. default:
  265. define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL);
  266. }
  267. }
  268. switch ( MATH_BIGINTEGER_MODE ) {
  269. case MATH_BIGINTEGER_MODE_GMP:
  270. if (is_resource($x) && get_resource_type($x) == 'GMP integer') {
  271. $this->value = $x;
  272. return;
  273. }
  274. $this->value = gmp_init(0);
  275. break;
  276. case MATH_BIGINTEGER_MODE_BCMATH:
  277. $this->value = '0';
  278. break;
  279. default:
  280. $this->value = array();
  281. }
  282. if (empty($x)) {
  283. return;
  284. }
  285. switch ($base) {
  286. case -256:
  287. if (ord($x[0]) & 0x80) {
  288. $x = ~$x;
  289. $this->is_negative = true;
  290. }
  291. case 256:
  292. switch ( MATH_BIGINTEGER_MODE ) {
  293. case MATH_BIGINTEGER_MODE_GMP:
  294. $sign = $this->is_negative ? '-' : '';
  295. $this->value = gmp_init($sign . '0x' . bin2hex($x));
  296. break;
  297. case MATH_BIGINTEGER_MODE_BCMATH:
  298. // round $len to the nearest 4 (thanks, DavidMJ!)
  299. $len = (strlen($x) + 3) & 0xFFFFFFFC;
  300. $x = str_pad($x, $len, chr(0), STR_PAD_LEFT);
  301. for ($i = 0; $i < $len; $i+= 4) {
  302. $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32
  303. $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0);
  304. }
  305. if ($this->is_negative) {
  306. $this->value = '-' . $this->value;
  307. }
  308. break;
  309. // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb)
  310. default:
  311. while (strlen($x)) {
  312. $this->value[] = $this->_bytes2int($this->_base256_rshift($x, 26));
  313. }
  314. }
  315. if ($this->is_negative) {
  316. if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) {
  317. $this->is_negative = false;
  318. }
  319. $temp = $this->add(new Math_BigInteger('-1'));
  320. $this->value = $temp->value;
  321. }
  322. break;
  323. case 16:
  324. case -16:
  325. if ($base > 0 && $x[0] == '-') {
  326. $this->is_negative = true;
  327. $x = substr($x, 1);
  328. }
  329. $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x);
  330. $is_negative = false;
  331. if ($base < 0 && hexdec($x[0]) >= 8) {
  332. $this->is_negative = $is_negative = true;
  333. $x = bin2hex(~pack('H*', $x));
  334. }
  335. switch ( MATH_BIGINTEGER_MODE ) {
  336. case MATH_BIGINTEGER_MODE_GMP:
  337. $temp = $this->is_negative ? '-0x' . $x : '0x' . $x;
  338. $this->value = gmp_init($temp);
  339. $this->is_negative = false;
  340. break;
  341. case MATH_BIGINTEGER_MODE_BCMATH:
  342. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  343. $temp = new Math_BigInteger(pack('H*', $x), 256);
  344. $this->value = $this->is_negative ? '-' . $temp->value : $temp->value;
  345. $this->is_negative = false;
  346. break;
  347. default:
  348. $x = ( strlen($x) & 1 ) ? '0' . $x : $x;
  349. $temp = new Math_BigInteger(pack('H*', $x), 256);
  350. $this->value = $temp->value;
  351. }
  352. if ($is_negative) {
  353. $temp = $this->add(new Math_BigInteger('-1'));
  354. $this->value = $temp->value;
  355. }
  356. break;
  357. case 10:
  358. case -10:
  359. $x = preg_replace('#^(-?[0-9]*).*#', '$1', $x);
  360. switch ( MATH_BIGINTEGER_MODE ) {
  361. case MATH_BIGINTEGER_MODE_GMP:
  362. $this->value = gmp_init($x);
  363. break;
  364. case MATH_BIGINTEGER_MODE_BCMATH:
  365. // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different
  366. // results then doing it on '-1' does (modInverse does $x[0])
  367. $this->value = (string) $x;
  368. break;
  369. default:
  370. $temp = new Math_BigInteger();
  371. // array(10000000) is 10**7 in base-2**26. 10**7 is the closest to 2**26 we can get without passing it.
  372. $multiplier = new Math_BigInteger();
  373. $multiplier->value = array(10000000);
  374. if ($x[0] == '-') {
  375. $this->is_negative = true;
  376. $x = substr($x, 1);
  377. }
  378. $x = str_pad($x, strlen($x) + (6 * strlen($x)) % 7, 0, STR_PAD_LEFT);
  379. while (strlen($x)) {
  380. $temp = $temp->multiply($multiplier);
  381. $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, 7)), 256));
  382. $x = substr($x, 7);
  383. }
  384. $this->value = $temp->value;
  385. }
  386. break;
  387. case 2: // base-2 support originally implemented by Lluis Pamies - thanks!
  388. case -2:
  389. if ($base > 0 && $x[0] == '-') {
  390. $this->is_negative = true;
  391. $x = substr($x, 1);
  392. }
  393. $x = preg_replace('#^([01]*).*#', '$1', $x);
  394. $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT);
  395. $str = '0x';
  396. while (strlen($x)) {
  397. $part = substr($x, 0, 4);
  398. $str.= dechex(bindec($part));
  399. $x = substr($x, 4);
  400. }
  401. if ($this->is_negative) {
  402. $str = '-' . $str;
  403. }
  404. $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16
  405. $this->value = $temp->value;
  406. $this->is_negative = $temp->is_negative;
  407. break;
  408. default:
  409. // base not supported, so we'll let $this == 0
  410. }
  411. }
  412. /**
  413. * Converts a BigInteger to a byte string (eg. base-256).
  414. *
  415. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  416. * saved as two's compliment.
  417. *
  418. * Here's an example:
  419. * <code>
  420. * <?php
  421. * include('Math/BigInteger.php');
  422. *
  423. * $a = new Math_BigInteger('65');
  424. *
  425. * echo $a->toBytes(); // outputs chr(65)
  426. * ?>
  427. * </code>
  428. *
  429. * @param Boolean $twos_compliment
  430. * @return String
  431. * @access public
  432. * @internal Converts a base-2**26 number to base-2**8
  433. */
  434. function toBytes($twos_compliment = false)
  435. {
  436. if ($twos_compliment) {
  437. $comparison = $this->compare(new Math_BigInteger());
  438. if ($comparison == 0) {
  439. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  440. }
  441. $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->copy();
  442. $bytes = $temp->toBytes();
  443. if (empty($bytes)) { // eg. if the number we're trying to convert is -1
  444. $bytes = chr(0);
  445. }
  446. if (ord($bytes[0]) & 0x80) {
  447. $bytes = chr(0) . $bytes;
  448. }
  449. return $comparison < 0 ? ~$bytes : $bytes;
  450. }
  451. switch ( MATH_BIGINTEGER_MODE ) {
  452. case MATH_BIGINTEGER_MODE_GMP:
  453. if (gmp_cmp($this->value, gmp_init(0)) == 0) {
  454. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  455. }
  456. $temp = gmp_strval(gmp_abs($this->value), 16);
  457. $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp;
  458. $temp = pack('H*', $temp);
  459. return $this->precision > 0 ?
  460. substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  461. ltrim($temp, chr(0));
  462. case MATH_BIGINTEGER_MODE_BCMATH:
  463. if ($this->value === '0') {
  464. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  465. }
  466. $value = '';
  467. $current = $this->value;
  468. if ($current[0] == '-') {
  469. $current = substr($current, 1);
  470. }
  471. while (bccomp($current, '0', 0) > 0) {
  472. $temp = bcmod($current, '16777216');
  473. $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value;
  474. $current = bcdiv($current, '16777216', 0);
  475. }
  476. return $this->precision > 0 ?
  477. substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) :
  478. ltrim($value, chr(0));
  479. }
  480. if (!count($this->value)) {
  481. return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : '';
  482. }
  483. $result = $this->_int2bytes($this->value[count($this->value) - 1]);
  484. $temp = $this->copy();
  485. for ($i = count($temp->value) - 2; $i >= 0; --$i) {
  486. $temp->_base256_lshift($result, 26);
  487. $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT);
  488. }
  489. return $this->precision > 0 ?
  490. str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) :
  491. $result;
  492. }
  493. /**
  494. * Converts a BigInteger to a hex string (eg. base-16)).
  495. *
  496. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  497. * saved as two's compliment.
  498. *
  499. * Here's an example:
  500. * <code>
  501. * <?php
  502. * include('Math/BigInteger.php');
  503. *
  504. * $a = new Math_BigInteger('65');
  505. *
  506. * echo $a->toHex(); // outputs '41'
  507. * ?>
  508. * </code>
  509. *
  510. * @param Boolean $twos_compliment
  511. * @return String
  512. * @access public
  513. * @internal Converts a base-2**26 number to base-2**8
  514. */
  515. function toHex($twos_compliment = false)
  516. {
  517. return bin2hex($this->toBytes($twos_compliment));
  518. }
  519. /**
  520. * Converts a BigInteger to a bit string (eg. base-2).
  521. *
  522. * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're
  523. * saved as two's compliment.
  524. *
  525. * Here's an example:
  526. * <code>
  527. * <?php
  528. * include('Math/BigInteger.php');
  529. *
  530. * $a = new Math_BigInteger('65');
  531. *
  532. * echo $a->toBits(); // outputs '1000001'
  533. * ?>
  534. * </code>
  535. *
  536. * @param Boolean $twos_compliment
  537. * @return String
  538. * @access public
  539. * @internal Converts a base-2**26 number to base-2**2
  540. */
  541. function toBits($twos_compliment = false)
  542. {
  543. $hex = $this->toHex($twos_compliment);
  544. $bits = '';
  545. for ($i = 0; $i < strlen($hex); $i+=8) {
  546. $bits.= str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT);
  547. }
  548. return $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0');
  549. }
  550. /**
  551. * Converts a BigInteger to a base-10 number.
  552. *
  553. * Here's an example:
  554. * <code>
  555. * <?php
  556. * include('Math/BigInteger.php');
  557. *
  558. * $a = new Math_BigInteger('50');
  559. *
  560. * echo $a->toString(); // outputs 50
  561. * ?>
  562. * </code>
  563. *
  564. * @return String
  565. * @access public
  566. * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10)
  567. */
  568. function toString()
  569. {
  570. switch ( MATH_BIGINTEGER_MODE ) {
  571. case MATH_BIGINTEGER_MODE_GMP:
  572. return gmp_strval($this->value);
  573. case MATH_BIGINTEGER_MODE_BCMATH:
  574. if ($this->value === '0') {
  575. return '0';
  576. }
  577. return ltrim($this->value, '0');
  578. }
  579. if (!count($this->value)) {
  580. return '0';
  581. }
  582. $temp = $this->copy();
  583. $temp->is_negative = false;
  584. $divisor = new Math_BigInteger();
  585. $divisor->value = array(10000000); // eg. 10**7
  586. $result = '';
  587. while (count($temp->value)) {
  588. list($temp, $mod) = $temp->divide($divisor);
  589. $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', 7, '0', STR_PAD_LEFT) . $result;
  590. }
  591. $result = ltrim($result, '0');
  592. if (empty($result)) {
  593. $result = '0';
  594. }
  595. if ($this->is_negative) {
  596. $result = '-' . $result;
  597. }
  598. return $result;
  599. }
  600. /**
  601. * Copy an object
  602. *
  603. * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee
  604. * that all objects are passed by value, when appropriate. More information can be found here:
  605. *
  606. * {@link http://php.net/language.oop5.basic#51624}
  607. *
  608. * @access public
  609. * @see __clone()
  610. * @return Math_BigInteger
  611. */
  612. function copy()
  613. {
  614. $temp = new Math_BigInteger();
  615. $temp->value = $this->value;
  616. $temp->is_negative = $this->is_negative;
  617. $temp->generator = $this->generator;
  618. $temp->precision = $this->precision;
  619. $temp->bitmask = $this->bitmask;
  620. return $temp;
  621. }
  622. /**
  623. * __toString() magic method
  624. *
  625. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  626. * toString().
  627. *
  628. * @access public
  629. * @internal Implemented per a suggestion by Techie-Michael - thanks!
  630. */
  631. function __toString()
  632. {
  633. return $this->toString();
  634. }
  635. /**
  636. * __clone() magic method
  637. *
  638. * Although you can call Math_BigInteger::__toString() directly in PHP5, you cannot call Math_BigInteger::__clone()
  639. * directly in PHP5. You can in PHP4 since it's not a magic method, but in PHP5, you have to call it by using the PHP5
  640. * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5,
  641. * call Math_BigInteger::copy(), instead.
  642. *
  643. * @access public
  644. * @see copy()
  645. * @return Math_BigInteger
  646. */
  647. function __clone()
  648. {
  649. return $this->copy();
  650. }
  651. /**
  652. * __sleep() magic method
  653. *
  654. * Will be called, automatically, when serialize() is called on a Math_BigInteger object.
  655. *
  656. * @see __wakeup()
  657. * @access public
  658. */
  659. function __sleep()
  660. {
  661. $this->hex = $this->toHex(true);
  662. $vars = array('hex');
  663. if ($this->generator != 'mt_rand') {
  664. $vars[] = 'generator';
  665. }
  666. if ($this->precision > 0) {
  667. $vars[] = 'precision';
  668. }
  669. return $vars;
  670. }
  671. /**
  672. * __wakeup() magic method
  673. *
  674. * Will be called, automatically, when unserialize() is called on a Math_BigInteger object.
  675. *
  676. * @see __sleep()
  677. * @access public
  678. */
  679. function __wakeup()
  680. {
  681. $temp = new Math_BigInteger($this->hex, -16);
  682. $this->value = $temp->value;
  683. $this->is_negative = $temp->is_negative;
  684. $this->setRandomGenerator($this->generator);
  685. if ($this->precision > 0) {
  686. // recalculate $this->bitmask
  687. $this->setPrecision($this->precision);
  688. }
  689. }
  690. /**
  691. * Adds two BigIntegers.
  692. *
  693. * Here's an example:
  694. * <code>
  695. * <?php
  696. * include('Math/BigInteger.php');
  697. *
  698. * $a = new Math_BigInteger('10');
  699. * $b = new Math_BigInteger('20');
  700. *
  701. * $c = $a->add($b);
  702. *
  703. * echo $c->toString(); // outputs 30
  704. * ?>
  705. * </code>
  706. *
  707. * @param Math_BigInteger $y
  708. * @return Math_BigInteger
  709. * @access public
  710. * @internal Performs base-2**52 addition
  711. */
  712. function add($y)
  713. {
  714. switch ( MATH_BIGINTEGER_MODE ) {
  715. case MATH_BIGINTEGER_MODE_GMP:
  716. $temp = new Math_BigInteger();
  717. $temp->value = gmp_add($this->value, $y->value);
  718. return $this->_normalize($temp);
  719. case MATH_BIGINTEGER_MODE_BCMATH:
  720. $temp = new Math_BigInteger();
  721. $temp->value = bcadd($this->value, $y->value, 0);
  722. return $this->_normalize($temp);
  723. }
  724. $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative);
  725. $result = new Math_BigInteger();
  726. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  727. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  728. return $this->_normalize($result);
  729. }
  730. /**
  731. * Performs addition.
  732. *
  733. * @param Array $x_value
  734. * @param Boolean $x_negative
  735. * @param Array $y_value
  736. * @param Boolean $y_negative
  737. * @return Array
  738. * @access private
  739. */
  740. function _add($x_value, $x_negative, $y_value, $y_negative)
  741. {
  742. $x_size = count($x_value);
  743. $y_size = count($y_value);
  744. if ($x_size == 0) {
  745. return array(
  746. MATH_BIGINTEGER_VALUE => $y_value,
  747. MATH_BIGINTEGER_SIGN => $y_negative
  748. );
  749. } else if ($y_size == 0) {
  750. return array(
  751. MATH_BIGINTEGER_VALUE => $x_value,
  752. MATH_BIGINTEGER_SIGN => $x_negative
  753. );
  754. }
  755. // subtract, if appropriate
  756. if ( $x_negative != $y_negative ) {
  757. if ( $x_value == $y_value ) {
  758. return array(
  759. MATH_BIGINTEGER_VALUE => array(),
  760. MATH_BIGINTEGER_SIGN => false
  761. );
  762. }
  763. $temp = $this->_subtract($x_value, false, $y_value, false);
  764. $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ?
  765. $x_negative : $y_negative;
  766. return $temp;
  767. }
  768. if ($x_size < $y_size) {
  769. $size = $x_size;
  770. $value = $y_value;
  771. } else {
  772. $size = $y_size;
  773. $value = $x_value;
  774. }
  775. $value[] = 0; // just in case the carry adds an extra digit
  776. $carry = 0;
  777. for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) {
  778. $sum = $x_value[$j] * 0x4000000 + $x_value[$i] + $y_value[$j] * 0x4000000 + $y_value[$i] + $carry;
  779. $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT52; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  780. $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  781. $temp = (int) ($sum / 0x4000000);
  782. $value[$i] = (int) ($sum - 0x4000000 * $temp); // eg. a faster alternative to fmod($sum, 0x4000000)
  783. $value[$j] = $temp;
  784. }
  785. if ($j == $size) { // ie. if $y_size is odd
  786. $sum = $x_value[$i] + $y_value[$i] + $carry;
  787. $carry = $sum >= 0x4000000;
  788. $value[$i] = $carry ? $sum - 0x4000000 : $sum;
  789. ++$i; // ie. let $i = $j since we've just done $value[$i]
  790. }
  791. if ($carry) {
  792. for (; $value[$i] == 0x3FFFFFF; ++$i) {
  793. $value[$i] = 0;
  794. }
  795. ++$value[$i];
  796. }
  797. return array(
  798. MATH_BIGINTEGER_VALUE => $this->_trim($value),
  799. MATH_BIGINTEGER_SIGN => $x_negative
  800. );
  801. }
  802. /**
  803. * Subtracts two BigIntegers.
  804. *
  805. * Here's an example:
  806. * <code>
  807. * <?php
  808. * include('Math/BigInteger.php');
  809. *
  810. * $a = new Math_BigInteger('10');
  811. * $b = new Math_BigInteger('20');
  812. *
  813. * $c = $a->subtract($b);
  814. *
  815. * echo $c->toString(); // outputs -10
  816. * ?>
  817. * </code>
  818. *
  819. * @param Math_BigInteger $y
  820. * @return Math_BigInteger
  821. * @access public
  822. * @internal Performs base-2**52 subtraction
  823. */
  824. function subtract($y)
  825. {
  826. switch ( MATH_BIGINTEGER_MODE ) {
  827. case MATH_BIGINTEGER_MODE_GMP:
  828. $temp = new Math_BigInteger();
  829. $temp->value = gmp_sub($this->value, $y->value);
  830. return $this->_normalize($temp);
  831. case MATH_BIGINTEGER_MODE_BCMATH:
  832. $temp = new Math_BigInteger();
  833. $temp->value = bcsub($this->value, $y->value, 0);
  834. return $this->_normalize($temp);
  835. }
  836. $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative);
  837. $result = new Math_BigInteger();
  838. $result->value = $temp[MATH_BIGINTEGER_VALUE];
  839. $result->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  840. return $this->_normalize($result);
  841. }
  842. /**
  843. * Performs subtraction.
  844. *
  845. * @param Array $x_value
  846. * @param Boolean $x_negative
  847. * @param Array $y_value
  848. * @param Boolean $y_negative
  849. * @return Array
  850. * @access private
  851. */
  852. function _subtract($x_value, $x_negative, $y_value, $y_negative)
  853. {
  854. $x_size = count($x_value);
  855. $y_size = count($y_value);
  856. if ($x_size == 0) {
  857. return array(
  858. MATH_BIGINTEGER_VALUE => $y_value,
  859. MATH_BIGINTEGER_SIGN => !$y_negative
  860. );
  861. } else if ($y_size == 0) {
  862. return array(
  863. MATH_BIGINTEGER_VALUE => $x_value,
  864. MATH_BIGINTEGER_SIGN => $x_negative
  865. );
  866. }
  867. // add, if appropriate (ie. -$x - +$y or +$x - -$y)
  868. if ( $x_negative != $y_negative ) {
  869. $temp = $this->_add($x_value, false, $y_value, false);
  870. $temp[MATH_BIGINTEGER_SIGN] = $x_negative;
  871. return $temp;
  872. }
  873. $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative);
  874. if ( !$diff ) {
  875. return array(
  876. MATH_BIGINTEGER_VALUE => array(),
  877. MATH_BIGINTEGER_SIGN => false
  878. );
  879. }
  880. // switch $x and $y around, if appropriate.
  881. if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) {
  882. $temp = $x_value;
  883. $x_value = $y_value;
  884. $y_value = $temp;
  885. $x_negative = !$x_negative;
  886. $x_size = count($x_value);
  887. $y_size = count($y_value);
  888. }
  889. // at this point, $x_value should be at least as big as - if not bigger than - $y_value
  890. $carry = 0;
  891. for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) {
  892. $sum = $x_value[$j] * 0x4000000 + $x_value[$i] - $y_value[$j] * 0x4000000 - $y_value[$i] - $carry;
  893. $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1
  894. $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT52 : $sum;
  895. $temp = (int) ($sum / 0x4000000);
  896. $x_value[$i] = (int) ($sum - 0x4000000 * $temp);
  897. $x_value[$j] = $temp;
  898. }
  899. if ($j == $y_size) { // ie. if $y_size is odd
  900. $sum = $x_value[$i] - $y_value[$i] - $carry;
  901. $carry = $sum < 0;
  902. $x_value[$i] = $carry ? $sum + 0x4000000 : $sum;
  903. ++$i;
  904. }
  905. if ($carry) {
  906. for (; !$x_value[$i]; ++$i) {
  907. $x_value[$i] = 0x3FFFFFF;
  908. }
  909. --$x_value[$i];
  910. }
  911. return array(
  912. MATH_BIGINTEGER_VALUE => $this->_trim($x_value),
  913. MATH_BIGINTEGER_SIGN => $x_negative
  914. );
  915. }
  916. /**
  917. * Multiplies two BigIntegers
  918. *
  919. * Here's an example:
  920. * <code>
  921. * <?php
  922. * include('Math/BigInteger.php');
  923. *
  924. * $a = new Math_BigInteger('10');
  925. * $b = new Math_BigInteger('20');
  926. *
  927. * $c = $a->multiply($b);
  928. *
  929. * echo $c->toString(); // outputs 200
  930. * ?>
  931. * </code>
  932. *
  933. * @param Math_BigInteger $x
  934. * @return Math_BigInteger
  935. * @access public
  936. */
  937. function multiply($x)
  938. {
  939. switch ( MATH_BIGINTEGER_MODE ) {
  940. case MATH_BIGINTEGER_MODE_GMP:
  941. $temp = new Math_BigInteger();
  942. $temp->value = gmp_mul($this->value, $x->value);
  943. return $this->_normalize($temp);
  944. case MATH_BIGINTEGER_MODE_BCMATH:
  945. $temp = new Math_BigInteger();
  946. $temp->value = bcmul($this->value, $x->value, 0);
  947. return $this->_normalize($temp);
  948. }
  949. $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative);
  950. $product = new Math_BigInteger();
  951. $product->value = $temp[MATH_BIGINTEGER_VALUE];
  952. $product->is_negative = $temp[MATH_BIGINTEGER_SIGN];
  953. return $this->_normalize($product);
  954. }
  955. /**
  956. * Performs multiplication.
  957. *
  958. * @param Array $x_value
  959. * @param Boolean $x_negative
  960. * @param Array $y_value
  961. * @param Boolean $y_negative
  962. * @return Array
  963. * @access private
  964. */
  965. function _multiply($x_value, $x_negative, $y_value, $y_negative)
  966. {
  967. //if ( $x_value == $y_value ) {
  968. // return array(
  969. // MATH_BIGINTEGER_VALUE => $this->_square($x_value),
  970. // MATH_BIGINTEGER_SIGN => $x_sign != $y_value
  971. // );
  972. //}
  973. $x_length = count($x_value);
  974. $y_length = count($y_value);
  975. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  976. return array(
  977. MATH_BIGINTEGER_VALUE => array(),
  978. MATH_BIGINTEGER_SIGN => false
  979. );
  980. }
  981. return array(
  982. MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  983. $this->_trim($this->_regularMultiply($x_value, $y_value)) :
  984. $this->_trim($this->_karatsuba($x_value, $y_value)),
  985. MATH_BIGINTEGER_SIGN => $x_negative != $y_negative
  986. );
  987. }
  988. /**
  989. * Performs long multiplication on two BigIntegers
  990. *
  991. * Modeled after 'multiply' in MutableBigInteger.java.
  992. *
  993. * @param Array $x_value
  994. * @param Array $y_value
  995. * @return Array
  996. * @access private
  997. */
  998. function _regularMultiply($x_value, $y_value)
  999. {
  1000. $x_length = count($x_value);
  1001. $y_length = count($y_value);
  1002. if ( !$x_length || !$y_length ) { // a 0 is being multiplied
  1003. return array();
  1004. }
  1005. if ( $x_length < $y_length ) {
  1006. $temp = $x_value;
  1007. $x_value = $y_value;
  1008. $y_value = $temp;
  1009. $x_length = count($x_value);
  1010. $y_length = count($y_value);
  1011. }
  1012. $product_value = $this->_array_repeat(0, $x_length + $y_length);
  1013. // the following for loop could be removed if the for loop following it
  1014. // (the one with nested for loops) initially set $i to 0, but
  1015. // doing so would also make the result in one set of unnecessary adds,
  1016. // since on the outermost loops first pass, $product->value[$k] is going
  1017. // to always be 0
  1018. $carry = 0;
  1019. for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0
  1020. $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0
  1021. $carry = (int) ($temp / 0x4000000);
  1022. $product_value[$j] = (int) ($temp - 0x4000000 * $carry);
  1023. }
  1024. $product_value[$j] = $carry;
  1025. // the above for loop is what the previous comment was talking about. the
  1026. // following for loop is the "one with nested for loops"
  1027. for ($i = 1; $i < $y_length; ++$i) {
  1028. $carry = 0;
  1029. for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) {
  1030. $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry;
  1031. $carry = (int) ($temp / 0x4000000);
  1032. $product_value[$k] = (int) ($temp - 0x4000000 * $carry);
  1033. }
  1034. $product_value[$k] = $carry;
  1035. }
  1036. return $product_value;
  1037. }
  1038. /**
  1039. * Performs Karatsuba multiplication on two BigIntegers
  1040. *
  1041. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1042. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}.
  1043. *
  1044. * @param Array $x_value
  1045. * @param Array $y_value
  1046. * @return Array
  1047. * @access private
  1048. */
  1049. function _karatsuba($x_value, $y_value)
  1050. {
  1051. $m = min(count($x_value) >> 1, count($y_value) >> 1);
  1052. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1053. return $this->_regularMultiply($x_value, $y_value);
  1054. }
  1055. $x1 = array_slice($x_value, $m);
  1056. $x0 = array_slice($x_value, 0, $m);
  1057. $y1 = array_slice($y_value, $m);
  1058. $y0 = array_slice($y_value, 0, $m);
  1059. $z2 = $this->_karatsuba($x1, $y1);
  1060. $z0 = $this->_karatsuba($x0, $y0);
  1061. $z1 = $this->_add($x1, false, $x0, false);
  1062. $temp = $this->_add($y1, false, $y0, false);
  1063. $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]);
  1064. $temp = $this->_add($z2, false, $z0, false);
  1065. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1066. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1067. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1068. $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1069. $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false);
  1070. return $xy[MATH_BIGINTEGER_VALUE];
  1071. }
  1072. /**
  1073. * Performs squaring
  1074. *
  1075. * @param Array $x
  1076. * @return Array
  1077. * @access private
  1078. */
  1079. function _square($x = false)
  1080. {
  1081. return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ?
  1082. $this->_trim($this->_baseSquare($x)) :
  1083. $this->_trim($this->_karatsubaSquare($x));
  1084. }
  1085. /**
  1086. * Performs traditional squaring on two BigIntegers
  1087. *
  1088. * Squaring can be done faster than multiplying a number by itself can be. See
  1089. * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} /
  1090. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information.
  1091. *
  1092. * @param Array $value
  1093. * @return Array
  1094. * @access private
  1095. */
  1096. function _baseSquare($value)
  1097. {
  1098. if ( empty($value) ) {
  1099. return array();
  1100. }
  1101. $square_value = $this->_array_repeat(0, 2 * count($value));
  1102. for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) {
  1103. $i2 = $i << 1;
  1104. $temp = $square_value[$i2] + $value[$i] * $value[$i];
  1105. $carry = (int) ($temp / 0x4000000);
  1106. $square_value[$i2] = (int) ($temp - 0x4000000 * $carry);
  1107. // note how we start from $i+1 instead of 0 as we do in multiplication.
  1108. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) {
  1109. $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry;
  1110. $carry = (int) ($temp / 0x4000000);
  1111. $square_value[$k] = (int) ($temp - 0x4000000 * $carry);
  1112. }
  1113. // the following line can yield values larger 2**15. at this point, PHP should switch
  1114. // over to floats.
  1115. $square_value[$i + $max_index + 1] = $carry;
  1116. }
  1117. return $square_value;
  1118. }
  1119. /**
  1120. * Performs Karatsuba "squaring" on two BigIntegers
  1121. *
  1122. * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and
  1123. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}.
  1124. *
  1125. * @param Array $value
  1126. * @return Array
  1127. * @access private
  1128. */
  1129. function _karatsubaSquare($value)
  1130. {
  1131. $m = count($value) >> 1;
  1132. if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) {
  1133. return $this->_baseSquare($value);
  1134. }
  1135. $x1 = array_slice($value, $m);
  1136. $x0 = array_slice($value, 0, $m);
  1137. $z2 = $this->_karatsubaSquare($x1);
  1138. $z0 = $this->_karatsubaSquare($x0);
  1139. $z1 = $this->_add($x1, false, $x0, false);
  1140. $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]);
  1141. $temp = $this->_add($z2, false, $z0, false);
  1142. $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false);
  1143. $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2);
  1144. $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]);
  1145. $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]);
  1146. $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false);
  1147. return $xx[MATH_BIGINTEGER_VALUE];
  1148. }
  1149. /**
  1150. * Divides two BigIntegers.
  1151. *
  1152. * Returns an array whose first element contains the quotient and whose second element contains the
  1153. * "common residue". If the remainder would be positive, the "common residue" and the remainder are the
  1154. * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder
  1155. * and the divisor (basically, the "common residue" is the first positive modulo).
  1156. *
  1157. * Here's an example:
  1158. * <code>
  1159. * <?php
  1160. * include('Math/BigInteger.php');
  1161. *
  1162. * $a = new Math_BigInteger('10');
  1163. * $b = new Math_BigInteger('20');
  1164. *
  1165. * list($quotient, $remainder) = $a->divide($b);
  1166. *
  1167. * echo $quotient->toString(); // outputs 0
  1168. * echo "\r\n";
  1169. * echo $remainder->toString(); // outputs 10
  1170. * ?>
  1171. * </code>
  1172. *
  1173. * @param Math_BigInteger $y
  1174. * @return Array
  1175. * @access public
  1176. * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}.
  1177. */
  1178. function divide($y)
  1179. {
  1180. switch ( MATH_BIGINTEGER_MODE ) {
  1181. case MATH_BIGINTEGER_MODE_GMP:
  1182. $quotient = new Math_BigInteger();
  1183. $remainder = new Math_BigInteger();
  1184. list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value);
  1185. if (gmp_sign($remainder->value) < 0) {
  1186. $remainder->value = gmp_add($remainder->value, gmp_abs($y->value));
  1187. }
  1188. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1189. case MATH_BIGINTEGER_MODE_BCMATH:
  1190. $quotient = new Math_BigInteger();
  1191. $remainder = new Math_BigInteger();
  1192. $quotient->value = bcdiv($this->value, $y->value, 0);
  1193. $remainder->value = bcmod($this->value, $y->value);
  1194. if ($remainder->value[0] == '-') {
  1195. $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0);
  1196. }
  1197. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1198. }
  1199. if (count($y->value) == 1) {
  1200. list($q, $r) = $this->_divide_digit($this->value, $y->value[0]);
  1201. $quotient = new Math_BigInteger();
  1202. $remainder = new Math_BigInteger();
  1203. $quotient->value = $q;
  1204. $remainder->value = array($r);
  1205. $quotient->is_negative = $this->is_negative != $y->is_negative;
  1206. return array($this->_normalize($quotient), $this->_normalize($remainder));
  1207. }
  1208. static $zero;
  1209. if ( !isset($zero) ) {
  1210. $zero = new Math_BigInteger();
  1211. }
  1212. $x = $this->copy();
  1213. $y = $y->copy();
  1214. $x_sign = $x->is_negative;
  1215. $y_sign = $y->is_negative;
  1216. $x->is_negative = $y->is_negative = false;
  1217. $diff = $x->compare($y);
  1218. if ( !$diff ) {
  1219. $temp = new Math_BigInteger();
  1220. $temp->value = array(1);
  1221. $temp->is_negative = $x_sign != $y_sign;
  1222. return array($this->_normalize($temp), $this->_normalize(new Math_BigInteger()));
  1223. }
  1224. if ( $diff < 0 ) {
  1225. // if $x is negative, "add" $y.
  1226. if ( $x_sign ) {
  1227. $x = $y->subtract($x);
  1228. }
  1229. return array($this->_normalize(new Math_BigInteger()), $this->_normalize($x));
  1230. }
  1231. // normalize $x and $y as described in HAC 14.23 / 14.24
  1232. $msb = $y->value[count($y->value) - 1];
  1233. for ($shift = 0; !($msb & 0x2000000); ++$shift) {
  1234. $msb <<= 1;
  1235. }
  1236. $x->_lshift($shift);
  1237. $y->_lshift($shift);
  1238. $y_value = &$y->value;
  1239. $x_max = count($x->value) - 1;
  1240. $y_max = count($y->value) - 1;
  1241. $quotient = new Math_BigInteger();
  1242. $quotient_value = &$quotient->value;
  1243. $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1);
  1244. static $temp, $lhs, $rhs;
  1245. if (!isset($temp)) {
  1246. $temp = new Math_BigInteger();
  1247. $lhs = new Math_BigInteger();
  1248. $rhs = new Math_BigInteger();
  1249. }
  1250. $temp_value = &$temp->value;
  1251. $rhs_value = &$rhs->value;
  1252. // $temp = $y << ($x_max - $y_max-1) in base 2**26
  1253. $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value);
  1254. while ( $x->compare($temp) >= 0 ) {
  1255. // calculate the "common residue"
  1256. ++$quotient_value[$x_max - $y_max];
  1257. $x = $x->subtract($temp);
  1258. $x_max = count($x->value) - 1;
  1259. }
  1260. for ($i = $x_max; $i >= $y_max + 1; --$i) {
  1261. $x_value = &$x->value;
  1262. $x_window = array(
  1263. isset($x_value[$i]) ? $x_value[$i] : 0,
  1264. isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0,
  1265. isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0
  1266. );
  1267. $y_window = array(
  1268. $y_value[$y_max],
  1269. ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0
  1270. );
  1271. $q_index = $i - $y_max - 1;
  1272. if ($x_window[0] == $y_window[0]) {
  1273. $quotient_value[$q_index] = 0x3FFFFFF;
  1274. } else {
  1275. $quotient_value[$q_index] = (int) (
  1276. ($x_window[0] * 0x4000000 + $x_window[1])
  1277. /
  1278. $y_window[0]
  1279. );
  1280. }
  1281. $temp_value = array($y_window[1], $y_window[0]);
  1282. $lhs->value = array($quotient_value[$q_index]);
  1283. $lhs = $lhs->multiply($temp);
  1284. $rhs_value = array($x_window[2], $x_window[1], $x_window[0]);
  1285. while ( $lhs->compare($rhs) > 0 ) {
  1286. --$quotient_value[$q_index];
  1287. $lhs->value = array($quotient_value[$q_index]);
  1288. $lhs = $lhs->multiply($temp);
  1289. }
  1290. $adjust = $this->_array_repeat(0, $q_index);
  1291. $temp_value = array($quotient_value[$q_index]);
  1292. $temp = $temp->multiply($y);
  1293. $temp_value = &$temp->value;
  1294. $temp_value = array_merge($adjust, $temp_value);
  1295. $x = $x->subtract($temp);
  1296. if ($x->compare($zero) < 0) {
  1297. $temp_value = array_merge($adjust, $y_value);
  1298. $x = $x->add($temp);
  1299. --$quotient_value[$q_index];
  1300. }
  1301. $x_max = count($x_value) - 1;
  1302. }
  1303. // unnormalize the remainder
  1304. $x->_rshift($shift);
  1305. $quotient->is_negative = $x_sign != $y_sign;
  1306. // calculate the "common residue", if appropriate
  1307. if ( $x_sign ) {
  1308. $y->_rshift($shift);
  1309. $x = $y->subtract($x);
  1310. }
  1311. return array($this->_normalize($quotient), $this->_normalize($x));
  1312. }
  1313. /**
  1314. * Divides a BigInteger by a regular integer
  1315. *
  1316. * abc / x = a00 / x + b0 / x + c / x
  1317. *
  1318. * @param Array $dividend
  1319. * @param Array $divisor
  1320. * @return Array
  1321. * @access private
  1322. */
  1323. function _divide_digit($dividend, $divisor)
  1324. {
  1325. $carry = 0;
  1326. $result = array();
  1327. for ($i = count($dividend) - 1; $i >= 0; --$i) {
  1328. $temp = 0x4000000 * $carry + $dividend[$i];
  1329. $result[$i] = (int) ($temp / $divisor);
  1330. $carry = (int) ($temp - $divisor * $result[$i]);
  1331. }
  1332. return array($result, $carry);
  1333. }
  1334. /**
  1335. * Performs modular exponentiation.
  1336. *
  1337. * Here's an example:
  1338. * <code>
  1339. * <?php
  1340. * include('Math/BigInteger.php');
  1341. *
  1342. * $a = new Math_BigInteger('10');
  1343. * $b = new Math_BigInteger('20');
  1344. * $c = new Math_BigInteger('30');
  1345. *
  1346. * $c = $a->modPow($b, $c);

Large files files are truncated, but you can click here to view the full file