PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 1ms

/php5-3/core/tools/secure/math/BigInteger.class.php

https://bitbucket.org/ronaldobrandini/framework
PHP | 3608 lines | 1922 code | 484 blank | 1202 comment | 336 complexity | 49e1676d28bb691d5ba767dcbc937064 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception

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

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

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