PageRenderTime 57ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/phpseclib/Math/BigInteger.php

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

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