PageRenderTime 73ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/fuelphp/fuel/core/vendor/phpseclib/Math/BigInteger.php

http://github.com/eryx/php-framework-benchmark
PHP | 3553 lines | 1867 code | 467 blank | 1219 comment | 369 complexity | b63629d5d73d9701192d187f20705a99 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, Apache-2.0, LGPL-2.1, LGPL-3.0, BSD-2-Clause

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

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

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