PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/apps/files_external/3rdparty/phpseclib/phpseclib/Math/BigInteger.php

https://github.com/sezuan/core
PHP | 3633 lines | 1925 code | 483 blank | 1225 comment | 391 complexity | f6245348d3aa9e62240b00bafdfc8038 MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception

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

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