PageRenderTime 81ms CodeModel.GetById 40ms RepoModel.GetById 0ms app.codeStats 1ms

/system/expressionengine/third_party/updater/libraries/phpseclib/Math/BigInteger.php

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

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