PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/phpseclib/Math/BigInteger.php

https://github.com/floviolleau/Raspcontrol
PHP | 3650 lines | 1945 code | 482 blank | 1223 comment | 396 complexity | 191afb4fd1c6cf6ef0a5dc05e8d31222 MD5 | raw file
Possible License(s): GPL-2.0

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

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