PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/src/lib/phpseclib/Math/BigInteger.php

https://bitbucket.org/mkrasuski/magento-ce
PHP | 3545 lines | 1863 code | 466 blank | 1216 comment | 367 complexity | 8dd950e566864b28c92b58acb06e1535 MD5 | raw file

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

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