IntNum.java 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729
  1. // Copyright (c) 1997, 1998, 1999, 2000, 2006 Per M.A. Bothner.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.math;
  4. import java.io.*;
  5. import java.math.BigDecimal;
  6. import java.math.BigInteger;
  7. /** A class for infinite-precision integers.
  8. * @author Per Bothner
  9. */
  10. public class IntNum extends RatNum implements Externalizable
  11. {
  12. /** All integers are stored in 2's-complement form.
  13. * If words == null, the ival is the value of this IntNum.
  14. * Otherwise, the first ival elements of words make the value
  15. * of this IntNum, stored in little-endian order, 2's-complement form. */
  16. public int ival;
  17. public int[] words;
  18. /** We pre-allocate integers in the range minFixNum..maxFixNum. */
  19. static final int minFixNum = -100;
  20. static final int maxFixNum = 1024;
  21. static final int numFixNum = maxFixNum-minFixNum+1;
  22. static final IntNum[] smallFixNums = new IntNum[numFixNum];
  23. static {
  24. for (int i = numFixNum; --i >= 0; )
  25. smallFixNums[i] = new IntNum(i + minFixNum);
  26. }
  27. public IntNum ()
  28. {
  29. }
  30. /** Create a new (non-shared) IntNum, and initialize to an int.
  31. * @param value the initial value */
  32. public IntNum (int value)
  33. {
  34. ival = value;
  35. }
  36. public static final IntNum zero ()
  37. {
  38. return smallFixNums[- minFixNum];
  39. }
  40. public static final IntNum one ()
  41. {
  42. return smallFixNums[1 - minFixNum];
  43. }
  44. public static final IntNum ten ()
  45. {
  46. return smallFixNums[10 - minFixNum];
  47. }
  48. /** Return the IntNum for -1. */
  49. public static IntNum minusOne ()
  50. {
  51. return smallFixNums[-1 - minFixNum];
  52. }
  53. public static IntNum asIntNumOrNull (Object value)
  54. {
  55. if (value instanceof IntNum)
  56. return (IntNum) value;
  57. if (value instanceof UnsignedPrim)
  58. return ((UnsignedPrim) value).toIntNum();
  59. if (value instanceof BigInteger)
  60. return IntNum.valueOf(value.toString(), 10);
  61. if (value instanceof Number
  62. && (value instanceof Integer || value instanceof Long
  63. || value instanceof Short || value instanceof Byte))
  64. return IntNum.make(((Number) value).longValue());
  65. return null;
  66. }
  67. /** Allocate a new non-shared IntNum.
  68. * @param nwords number of words to allocate
  69. */
  70. public static IntNum alloc (int nwords)
  71. {
  72. if (nwords <= 1)
  73. return new IntNum ();
  74. IntNum result = new IntNum ();
  75. result.words = new int[nwords];
  76. return result;
  77. }
  78. /** Change words.length to nwords.
  79. * We allow words.length to be upto nwords+2 without reallocating. */
  80. public void realloc (int nwords)
  81. {
  82. if (nwords == 0)
  83. {
  84. if (words != null)
  85. {
  86. if (ival > 0)
  87. ival = words[0];
  88. words = null;
  89. }
  90. }
  91. else if (words == null
  92. || words.length < nwords
  93. || words.length > nwords + 2)
  94. {
  95. int[] new_words = new int [nwords];
  96. if (words == null)
  97. {
  98. new_words[0] = ival;
  99. ival = 1;
  100. }
  101. else
  102. {
  103. if (nwords < ival)
  104. ival = nwords;
  105. System.arraycopy (words, 0, new_words, 0, ival);
  106. }
  107. words = new_words;
  108. }
  109. }
  110. public final IntNum numerator ()
  111. {
  112. return this;
  113. }
  114. public final IntNum denominator ()
  115. {
  116. return one ();
  117. }
  118. public final boolean isNegative ()
  119. {
  120. return (words == null ? ival : words[ival-1]) < 0;
  121. }
  122. public int sign ()
  123. {
  124. int n = ival;
  125. int[] w = words;
  126. if (w == null)
  127. return n > 0 ? 1 : n < 0 ? -1 : 0;
  128. int i = w[--n];
  129. if (i > 0)
  130. return 1;
  131. if (i < 0)
  132. return -1;
  133. for (;;)
  134. {
  135. if (n == 0)
  136. return 0;
  137. if (w[--n] != 0)
  138. return 1;
  139. }
  140. }
  141. /** Return -1, 0, or 1, depending on which value is greater. */
  142. public static int compare (IntNum x, IntNum y)
  143. {
  144. if (x.words == null && y.words == null)
  145. return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
  146. boolean x_negative = x.isNegative ();
  147. boolean y_negative = y.isNegative ();
  148. if (x_negative != y_negative)
  149. return x_negative ? -1 : 1;
  150. int x_len = x.words == null ? 1 : x.ival;
  151. int y_len = y.words == null ? 1 : y.ival;
  152. if (x_len != y_len) // We assume x and y are canonicalized.
  153. return (x_len > y_len)!=x_negative ? 1 : -1;
  154. return MPN.cmp (x.words, y.words, x_len);
  155. }
  156. /** Return -1, 0, or 1, depending on which value is greater. */
  157. public static int compare (IntNum x, long y)
  158. {
  159. long x_word;
  160. if (x.words == null)
  161. x_word = x.ival;
  162. else
  163. {
  164. boolean x_negative = x.isNegative ();
  165. boolean y_negative = y < 0;
  166. if (x_negative != y_negative)
  167. return x_negative ? -1 : 1;
  168. int x_len = x.words == null ? 1 : x.ival;
  169. if (x_len == 1)
  170. x_word = x.words[0];
  171. else if (x_len == 2)
  172. x_word = x.longValue();
  173. else // We assume x is canonicalized.
  174. return x_negative ? -1 : 1;
  175. }
  176. return x_word < y ? -1 : x_word > y ? 1 : 0;
  177. }
  178. public int compare (Object obj)
  179. {
  180. if (obj instanceof IntNum)
  181. return compare (this, (IntNum) obj);
  182. return ((Numeric)obj).compareReversed (this);
  183. }
  184. public final boolean isOdd ()
  185. {
  186. int low = words == null ? ival : words[0];
  187. return (low & 1) != 0;
  188. }
  189. public final boolean isZero ()
  190. {
  191. return words == null && ival == 0;
  192. }
  193. public final boolean isOne ()
  194. {
  195. return words == null && ival == 1;
  196. }
  197. public final boolean isMinusOne ()
  198. {
  199. return words == null && ival == -1;
  200. }
  201. /** Calculate how many words are significant in words[0:len-1].
  202. * Returns the least value {@code x} such that
  203. * {@code x>0 && words[0:x-1]==words[0:len-1]},
  204. * when {@code words} is viewed as a 2's complement integer.
  205. */
  206. public static int wordsNeeded (int[] words, int len)
  207. {
  208. int i = len;
  209. if (i > 0)
  210. {
  211. int word = words[--i];
  212. if (word == -1)
  213. {
  214. while (i > 0 && (word = words[i-1]) < 0)
  215. {
  216. i--;
  217. if (word != -1) break;
  218. }
  219. }
  220. else
  221. {
  222. while (word == 0 && i > 0 && (word = words[i-1]) >= 0) i--;
  223. }
  224. }
  225. return i+1;
  226. }
  227. public IntNum canonicalize ()
  228. {
  229. if (words != null
  230. && (ival = IntNum.wordsNeeded (words, ival)) <= 1)
  231. {
  232. if (ival == 1)
  233. ival = words[0];
  234. words = null;
  235. }
  236. if (words == null && ival >= minFixNum && ival <= maxFixNum)
  237. return smallFixNums[(int) ival - minFixNum];
  238. return this;
  239. }
  240. /** Add two ints, yielding an IntNum. */
  241. public static final IntNum add (int x, int y)
  242. {
  243. return IntNum.make ((long) x + (long) y);
  244. }
  245. /** Add an IntNum and an int, yielding a new IntNum. */
  246. public static IntNum add (IntNum x, int y)
  247. {
  248. if (x.words == null)
  249. return IntNum.add (x.ival, y);
  250. IntNum result = new IntNum (0);
  251. result.setAdd (x, y);
  252. return result.canonicalize ();
  253. }
  254. /** Set this to the sum of x and y.
  255. * OK if x==this. */
  256. public void setAdd (IntNum x, int y)
  257. {
  258. if (x.words == null)
  259. {
  260. set ((long) x.ival + (long) y);
  261. return;
  262. }
  263. int len = x.ival;
  264. realloc (len + 1);
  265. long carry = y;
  266. for (int i = 0; i < len; i++)
  267. {
  268. carry += ((long) x.words[i] & 0xffffffffL);
  269. words[i] = (int) carry;
  270. carry >>= 32;
  271. }
  272. if (x.words[len - 1] < 0)
  273. carry--;
  274. words[len] = (int) carry;
  275. ival = wordsNeeded (words, len+1);
  276. }
  277. /** Destructively add an int to this. */
  278. public final void setAdd (int y)
  279. {
  280. setAdd (this, y);
  281. }
  282. /** Destructively set the value of this to an int. */
  283. public final void set (int y)
  284. {
  285. words = null;
  286. ival = y;
  287. }
  288. /** Destructively set the value of this to a long. */
  289. public final void set (long y)
  290. {
  291. int i = (int) y;
  292. if ((long) i == y)
  293. {
  294. ival = i;
  295. words = null;
  296. }
  297. else
  298. {
  299. realloc (2);
  300. words[0] = i;
  301. words[1] = (int) (y >> 32);
  302. ival = 2;
  303. }
  304. }
  305. /** Destructively set the value of this to the given words.
  306. * The words array is reused, not copied. */
  307. public final void set (int[] words, int length)
  308. {
  309. this.ival = length;
  310. this.words = words;
  311. }
  312. /** Destructively set the value of this to that of y. */
  313. public final void set (IntNum y)
  314. {
  315. if (y.words == null)
  316. set (y.ival);
  317. else if (this != y)
  318. {
  319. realloc(y.ival);
  320. System.arraycopy(y.words, 0, words, 0, y.ival);
  321. ival = y.ival;
  322. }
  323. }
  324. /** Add two IntNums, yielding their sum as another IntNum. */
  325. public static IntNum add (IntNum x, IntNum y)
  326. {
  327. return add(x, y, 1);
  328. }
  329. /** Subtract two IntNums, yielding their sum as another IntNum. */
  330. public static IntNum sub (IntNum x, IntNum y)
  331. {
  332. return add(x, y, -1);
  333. }
  334. /** Add two IntNums, yielding their sum as another IntNum. */
  335. public static IntNum add (IntNum x, IntNum y, int k)
  336. {
  337. if (y.words == null) {
  338. int yval = y.ival;
  339. if (yval == 0)
  340. return x;
  341. if (x.words == null)
  342. return IntNum.make((long) k * (long) yval + (long) x.ival);
  343. }
  344. if (k != 1)
  345. {
  346. if (k == -1)
  347. y = IntNum.neg (y);
  348. else
  349. y = IntNum.times (y, IntNum.make (k));
  350. }
  351. if (x.words == null)
  352. return IntNum.add (y, x.ival);
  353. if (y.words == null)
  354. return IntNum.add (x, y.ival);
  355. // Both are big
  356. int len;
  357. if (y.ival > x.ival)
  358. { // Swap so x is longer then y.
  359. IntNum tmp = x; x = y; y = tmp;
  360. }
  361. IntNum result = alloc (x.ival + 1);
  362. int i = y.ival;
  363. long carry = MPN.add_n (result.words, x.words, y.words, i);
  364. long y_ext = y.words[i-1] < 0 ? 0xffffffffL : 0;
  365. for (; i < x.ival; i++)
  366. {
  367. carry += ((long) x.words[i] & 0xffffffffL) + y_ext;;
  368. result.words[i] = (int) carry;
  369. carry >>>= 32;
  370. }
  371. if (x.words[i - 1] < 0)
  372. y_ext--;
  373. result.words[i] = (int) (carry + y_ext);
  374. result.ival = i+1;
  375. return result.canonicalize ();
  376. }
  377. /** Multiply two ints, yielding an IntNum. */
  378. public static final IntNum times (int x, int y)
  379. {
  380. return IntNum.make ((long) x * (long) y);
  381. }
  382. public static final IntNum times (IntNum x, int y)
  383. {
  384. if (y == 0)
  385. return zero();
  386. if (y == 1)
  387. return x;
  388. int[] xwords = x.words;
  389. int xlen = x.ival;
  390. if (xwords == null)
  391. return IntNum.make ((long) xlen * (long) y);
  392. boolean negative;
  393. IntNum result = IntNum.alloc (xlen+1);
  394. if (xwords[xlen-1] < 0)
  395. {
  396. negative = true;
  397. negate(result.words, xwords, xlen);
  398. xwords = result.words;
  399. }
  400. else
  401. negative = false;
  402. if (y < 0)
  403. {
  404. negative = !negative;
  405. y = -y;
  406. }
  407. result.words[xlen] = MPN.mul_1 (result.words, xwords, xlen, y);
  408. result.ival = xlen+1;
  409. if (negative)
  410. result.setNegative ();
  411. return result.canonicalize ();
  412. }
  413. public static final IntNum times (IntNum x, IntNum y)
  414. {
  415. if (y.words == null)
  416. return times(x, y.ival);
  417. if (x.words == null)
  418. return times(y, x.ival);
  419. boolean negative = false;
  420. int[] xwords;
  421. int[] ywords;
  422. int xlen = x.ival;
  423. int ylen = y.ival;
  424. if (x.isNegative ())
  425. {
  426. negative = true;
  427. xwords = new int[xlen];
  428. negate(xwords, x.words, xlen);
  429. }
  430. else
  431. {
  432. negative = false;
  433. xwords = x.words;
  434. }
  435. if (y.isNegative ())
  436. {
  437. negative = !negative;
  438. ywords = new int[ylen];
  439. negate(ywords, y.words, ylen);
  440. }
  441. else
  442. ywords = y.words;
  443. // Swap if x is shorter then y.
  444. if (xlen < ylen)
  445. {
  446. int[] twords = xwords; xwords = ywords; ywords = twords;
  447. int tlen = xlen; xlen = ylen; ylen = tlen;
  448. }
  449. IntNum result = IntNum.alloc (xlen+ylen);
  450. MPN.mul (result.words, xwords, xlen, ywords, ylen);
  451. result.ival = xlen+ylen;
  452. if (negative)
  453. result.setNegative ();
  454. return result.canonicalize ();
  455. }
  456. public static void divide (long x, long y,
  457. IntNum quotient, IntNum remainder,
  458. int rounding_mode)
  459. {
  460. boolean xNegative, yNegative;
  461. if (rounding_mode == NONNEG_MOD)
  462. rounding_mode = y < 0 ? CEILING : FLOOR;
  463. if (x < 0)
  464. {
  465. xNegative = true;
  466. if (x == Long.MIN_VALUE)
  467. {
  468. divide (IntNum.make (x), IntNum.make (y),
  469. quotient, remainder, rounding_mode);
  470. return;
  471. }
  472. x = -x;
  473. }
  474. else
  475. xNegative = false;
  476. if (y < 0)
  477. {
  478. yNegative = true;
  479. if (y == Long.MIN_VALUE)
  480. {
  481. if (rounding_mode == TRUNCATE)
  482. { // x != Long.Min_VALUE implies abs(x) < abs(y)
  483. if (quotient != null)
  484. quotient.set (0);
  485. if (remainder != null)
  486. remainder.set (x);
  487. }
  488. else
  489. divide (IntNum.make (x), IntNum.make (y),
  490. quotient, remainder, rounding_mode);
  491. return;
  492. }
  493. y = -y;
  494. }
  495. else
  496. yNegative = false;
  497. long q = x / y;
  498. long r = x % y;
  499. boolean qNegative = xNegative ^ yNegative;
  500. boolean add_one = false;
  501. if (r != 0)
  502. {
  503. switch (rounding_mode)
  504. {
  505. case TRUNCATE:
  506. break;
  507. case CEILING:
  508. case FLOOR:
  509. if (qNegative == (rounding_mode == FLOOR))
  510. add_one = true;
  511. break;
  512. case ROUND:
  513. add_one = r > ((y - (q & 1)) >> 1);
  514. break;
  515. }
  516. }
  517. if (quotient != null)
  518. {
  519. if (add_one)
  520. q++;
  521. if (qNegative)
  522. q = -q;
  523. quotient.set (q);
  524. }
  525. if (remainder != null)
  526. {
  527. // The remainder is by definition: X-Q*Y
  528. if (add_one)
  529. {
  530. // Subtract the remainder from Y.
  531. r = y - r;
  532. // In this case, abs(Q*Y) > abs(X).
  533. // So sign(remainder) = -sign(X).
  534. xNegative = ! xNegative;
  535. }
  536. else
  537. {
  538. // If !add_one, then: abs(Q*Y) <= abs(X).
  539. // So sign(remainder) = sign(X).
  540. }
  541. if (xNegative)
  542. r = -r;
  543. remainder.set (r);
  544. }
  545. }
  546. /** Divide two integers, yielding quotient and remainder.
  547. * @param x the numerator in the division
  548. * @param y the denominator in the division
  549. * @param quotient is set to the quotient of the result (iff quotient!=null)
  550. * @param remainder is set to the remainder of the result
  551. * (iff remainder!=null)
  552. * @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
  553. */
  554. public static void divide (IntNum x, IntNum y,
  555. IntNum quotient, IntNum remainder,
  556. int rounding_mode)
  557. {
  558. if ((x.words == null || x.ival <= 2)
  559. && (y.words == null || y.ival <= 2))
  560. {
  561. long x_l = x.longValue ();
  562. long y_l = y.longValue ();
  563. if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
  564. {
  565. divide (x_l, y_l, quotient, remainder, rounding_mode);
  566. return;
  567. }
  568. }
  569. boolean xNegative = x.isNegative ();
  570. boolean yNegative = y.isNegative ();
  571. boolean qNegative = xNegative ^ yNegative;
  572. int ylen = y.words == null ? 1 : y.ival;
  573. int[] ywords = new int[ylen];
  574. y.getAbsolute (ywords);
  575. while (ylen > 1 && ywords[ylen-1] == 0) ylen--;
  576. int xlen = x.words == null ? 1 : x.ival;
  577. int[] xwords = new int[xlen+2];
  578. x.getAbsolute (xwords);
  579. while (xlen > 1 && xwords[xlen-1] == 0) xlen--;
  580. int qlen, rlen;
  581. int cmpval = MPN.cmp (xwords, xlen, ywords, ylen);
  582. if (cmpval < 0) // abs(x) < abs(y)
  583. { // quotient = 0; remainder = num.
  584. int[] rwords = xwords; xwords = ywords; ywords = rwords;
  585. rlen = xlen; qlen = 1; xwords[0] = 0;
  586. }
  587. else if (cmpval == 0) // abs(x) == abs(y)
  588. {
  589. xwords[0] = 1; qlen = 1; // quotient = 1
  590. ywords[0] = 0; rlen = 1; // remainder = 0;
  591. }
  592. else if (ylen == 1)
  593. {
  594. qlen = xlen;
  595. rlen = 1;
  596. ywords[0] = MPN.divmod_1 (xwords, xwords, xlen, ywords[0]);
  597. }
  598. else // abs(x) > abs(y)
  599. {
  600. // Normalize the denominator, i.e. make its most significant bit set by
  601. // shifting it normalization_steps bits to the left. Also shift the
  602. // numerator the same number of steps (to keep the quotient the same!).
  603. int nshift = MPN.count_leading_zeros (ywords[ylen-1]);
  604. if (nshift != 0)
  605. {
  606. // Shift up the denominator setting the most significant bit of
  607. // the most significant word.
  608. MPN.lshift (ywords, 0, ywords, ylen, nshift);
  609. // Shift up the numerator, possibly introducing a new most
  610. // significant word.
  611. int x_high = MPN.lshift (xwords, 0, xwords, xlen, nshift);
  612. xwords[xlen++] = x_high;
  613. }
  614. if (xlen == ylen)
  615. xwords[xlen++] = 0;
  616. MPN.divide (xwords, xlen, ywords, ylen);
  617. rlen = ylen;
  618. MPN.rshift0 (ywords, xwords, 0, rlen, nshift);
  619. qlen = xlen + 1 - ylen;
  620. if (quotient != null)
  621. {
  622. for (int i = 0; i < qlen; i++)
  623. xwords[i] = xwords[i+ylen];
  624. }
  625. }
  626. while (rlen > 1 && ywords[rlen-1] == 0)
  627. rlen--;
  628. if (ywords[rlen-1] < 0)
  629. {
  630. ywords[rlen] = 0;
  631. rlen++;
  632. }
  633. // Now the quotient is in xwords, and the remainder is in ywords.
  634. boolean add_one = false;
  635. if (rlen > 1 || ywords[0] != 0)
  636. { // Non-zero remainder i.e. in-exact quotient.
  637. if (rounding_mode == NONNEG_MOD)
  638. {
  639. rounding_mode = yNegative ? CEILING : FLOOR;
  640. }
  641. switch (rounding_mode)
  642. {
  643. case TRUNCATE:
  644. break;
  645. case CEILING:
  646. case FLOOR:
  647. if (qNegative == (rounding_mode == FLOOR))
  648. add_one = true;
  649. break;
  650. case ROUND:
  651. // int cmp = compare (remainder<<1, abs(y));
  652. IntNum tmp = remainder == null ? new IntNum() : remainder;
  653. tmp.set (ywords, rlen);
  654. tmp = shift (tmp, 1);
  655. if (yNegative)
  656. tmp.setNegative();
  657. int cmp = compare (tmp, y);
  658. // Now cmp == compare(sign(y)*(remainder<<1), y)
  659. if (yNegative)
  660. cmp = -cmp;
  661. add_one = (cmp == 1) || (cmp == 0 && (xwords[0]&1) != 0);
  662. }
  663. }
  664. if (quotient != null)
  665. {
  666. if (xwords[qlen-1] < 0)
  667. {
  668. xwords[qlen] = 0;
  669. qlen++;
  670. }
  671. quotient.set (xwords, qlen);
  672. if (qNegative)
  673. {
  674. if (add_one) // -(quotient + 1) == ~(quotient)
  675. quotient.setInvert ();
  676. else
  677. quotient.setNegative ();
  678. }
  679. else if (add_one)
  680. quotient.setAdd (1);
  681. }
  682. if (remainder != null)
  683. {
  684. // The remainder is by definition: X-Q*Y
  685. remainder.set (ywords, rlen);
  686. if (add_one)
  687. {
  688. // Subtract the remainder from Y:
  689. // abs(R) = abs(Y) - abs(orig_rem) = -(abs(orig_rem) - abs(Y)).
  690. IntNum tmp;
  691. if (y.words == null)
  692. {
  693. tmp = remainder;
  694. tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
  695. }
  696. else
  697. tmp = IntNum.add(remainder, y, yNegative ? 1 : -1);
  698. // Now tmp <= 0.
  699. // In this case, abs(Q) = 1 + floor(abs(X)/abs(Y)).
  700. // Hence, abs(Q*Y) > abs(X).
  701. // So sign(remainder) = -sign(X).
  702. if (xNegative)
  703. remainder.setNegative(tmp);
  704. else
  705. remainder.set(tmp);
  706. }
  707. else
  708. {
  709. // If !add_one, then: abs(Q*Y) <= abs(X).
  710. // So sign(remainder) = sign(X).
  711. if (xNegative)
  712. remainder.setNegative ();
  713. }
  714. }
  715. }
  716. public static IntNum quotient (IntNum x, IntNum y, int rounding_mode)
  717. {
  718. IntNum quotient = new IntNum ();
  719. divide (x, y, quotient, null, rounding_mode);
  720. return quotient.canonicalize ();
  721. }
  722. public static IntNum quotient (IntNum x, IntNum y)
  723. {
  724. return quotient (x, y, TRUNCATE);
  725. }
  726. public IntNum toExactInt (int rounding_mode)
  727. {
  728. return this;
  729. }
  730. public RealNum toInt (int rounding_mode)
  731. {
  732. return this;
  733. }
  734. public static IntNum remainder (IntNum x, IntNum y, int rounding_mode)
  735. {
  736. if (y.isZero())
  737. return x;
  738. IntNum rem = new IntNum ();
  739. divide (x, y, null, rem, rounding_mode);
  740. return rem.canonicalize ();
  741. }
  742. public static IntNum remainder (IntNum x, IntNum y)
  743. {
  744. return remainder(x, y, TRUNCATE);
  745. }
  746. public static IntNum modulo (IntNum x, IntNum y)
  747. {
  748. return remainder(x, y, FLOOR);
  749. }
  750. public Numeric power (IntNum y)
  751. {
  752. if (isOne())
  753. return this;
  754. if (isMinusOne())
  755. return y.isOdd () ? this : IntNum.one ();
  756. if (y.words == null && y.ival >= 0)
  757. return power (this, y.ival);
  758. if (isZero())
  759. return y.isNegative () ? RatNum.infinity(-1) : (RatNum) this;
  760. return super.power (y);
  761. }
  762. /** Calculate the integral power of an IntNum.
  763. * @param x the value (base) to exponentiate
  764. * @param y the exponent (must be non-negative)
  765. */
  766. public static IntNum power (IntNum x, int y)
  767. {
  768. if (y <= 0)
  769. {
  770. if (y == 0)
  771. return one ();
  772. else
  773. throw new IllegalArgumentException("negative exponent");
  774. }
  775. if (x.isZero ())
  776. return x;
  777. int plen = x.words == null ? 1 : x.ival; // Length of pow2.
  778. int blen = ((x.intLength () * y) >> 5) + 2 * plen;
  779. boolean negative = x.isNegative () && (y & 1) != 0;
  780. int[] pow2 = new int [blen];
  781. int[] rwords = new int [blen];
  782. int[] work = new int [blen];
  783. x.getAbsolute (pow2); // pow2 = abs(x);
  784. int rlen = 1;
  785. rwords[0] = 1; // rwords = 1;
  786. for (;;) // for (i = 0; ; i++)
  787. {
  788. // pow2 == x**(2**i)
  789. // prod = x**(sum(j=0..i-1, (y>>j)&1))
  790. if ((y & 1) != 0)
  791. { // r *= pow2
  792. MPN.mul (work, pow2, plen, rwords, rlen);
  793. int[] temp = work; work = rwords; rwords = temp;
  794. rlen += plen;
  795. while (rwords[rlen-1] == 0) rlen--;
  796. }
  797. y >>= 1;
  798. if (y == 0)
  799. break;
  800. // pow2 *= pow2;
  801. MPN.mul (work, pow2, plen, pow2, plen);
  802. int[] temp = work; work = pow2; pow2 = temp; // swap to avoid a copy
  803. plen *= 2;
  804. while (pow2[plen-1] == 0) plen--;
  805. }
  806. if (rwords[rlen-1] < 0)
  807. rlen++;
  808. if (negative)
  809. negate (rwords, rwords, rlen);
  810. return IntNum.make (rwords, rlen);
  811. }
  812. /** Calculate Greatest Common Divisor for non-negative ints. */
  813. public static final int gcd (int a, int b)
  814. {
  815. // Euclid's algorithm, copied from libg++.
  816. if (b > a)
  817. {
  818. int tmp = a; a = b; b = tmp;
  819. }
  820. for(;;)
  821. {
  822. if (b == 0)
  823. return a;
  824. else if (b == 1)
  825. return b;
  826. else
  827. {
  828. int tmp = b;
  829. b = a % b;
  830. a = tmp;
  831. }
  832. }
  833. }
  834. public static IntNum gcd (IntNum x, IntNum y)
  835. {
  836. int xval = x.ival;
  837. int yval = y.ival;
  838. if (x.words == null)
  839. {
  840. if (xval == 0)
  841. return IntNum.abs(y);
  842. if (y.words == null
  843. && xval != Integer.MIN_VALUE && yval != Integer.MIN_VALUE)
  844. {
  845. if (xval < 0)
  846. xval = -xval;
  847. if (yval < 0)
  848. yval = -yval;
  849. return IntNum.make (IntNum.gcd (xval, yval));
  850. }
  851. xval = 1;
  852. }
  853. if (y.words == null)
  854. {
  855. if (yval == 0)
  856. return IntNum.abs(x);
  857. yval = 1;
  858. }
  859. int len = xval > yval ? xval : yval;
  860. int[] xwords = new int[len];
  861. int[] ywords = new int[len];
  862. x.getAbsolute (xwords);
  863. y.getAbsolute (ywords);
  864. len = MPN.gcd (xwords, ywords, len);
  865. IntNum result = new IntNum (0);
  866. // If the high-order bit in the result is set, the number needs one more
  867. // word to make the 2^er complement positive.
  868. if (xwords[len-1] < 0)
  869. xwords[len++] = 0;
  870. result.ival = len;
  871. result.words = xwords;
  872. return result.canonicalize ();
  873. }
  874. public static IntNum lcm (IntNum x, IntNum y)
  875. {
  876. if (x.isZero () || y.isZero ())
  877. return IntNum.zero ();
  878. x = IntNum.abs (x);
  879. y = IntNum.abs (y);
  880. IntNum quotient = new IntNum ();
  881. divide (times (x, y), gcd (x, y), quotient, null, TRUNCATE);
  882. return quotient.canonicalize ();
  883. }
  884. void setInvert ()
  885. {
  886. if (words == null)
  887. ival = ~ival;
  888. else
  889. {
  890. for (int i = ival; --i >= 0; )
  891. words[i] = ~words[i];
  892. }
  893. }
  894. void setShiftLeft (IntNum x, int count)
  895. {
  896. int[] xwords;
  897. int xlen;
  898. if (x.words == null)
  899. {
  900. if (count < 32)
  901. {
  902. set ((long) x.ival << count);
  903. return;
  904. }
  905. xwords = new int[1];
  906. xwords[0] = x.ival;
  907. xlen = 1;
  908. }
  909. else
  910. {
  911. xwords = x.words;
  912. xlen = x.ival;
  913. }
  914. int word_count = count >> 5;
  915. count &= 31;
  916. int new_len = xlen + word_count;
  917. if (count == 0)
  918. {
  919. realloc (new_len);
  920. for (int i = xlen; --i >= 0; )
  921. words[i+word_count] = xwords[i];
  922. }
  923. else
  924. {
  925. new_len++;
  926. realloc (new_len);
  927. int shift_out = MPN.lshift (words, word_count, xwords, xlen, count);
  928. count = 32 - count;
  929. words[new_len-1] = (shift_out << count) >> count; // sign-extend.
  930. }
  931. ival = new_len;
  932. for (int i = word_count; --i >= 0; )
  933. words[i] = 0;
  934. }
  935. void setShiftRight (IntNum x, int count)
  936. {
  937. if (x.words == null)
  938. set (count < 32 ? x.ival >> count : x.ival < 0 ? -1 : 0);
  939. else if (count == 0)
  940. set (x);
  941. else
  942. {
  943. boolean neg = x.isNegative ();
  944. int word_count = count >> 5;
  945. count &= 31;
  946. int d_len = x.ival - word_count;
  947. if (d_len <= 0)
  948. set (neg ? -1 : 0);
  949. else
  950. {
  951. if (words == null || words.length < d_len)
  952. realloc (d_len);
  953. MPN.rshift0 (words, x.words, word_count, d_len, count);
  954. ival = d_len;
  955. if (neg)
  956. words[d_len-1] |= -2 << (31 - count);
  957. }
  958. }
  959. }
  960. void setShift (IntNum x, int count)
  961. {
  962. if (count > 0)
  963. setShiftLeft (x, count);
  964. else
  965. setShiftRight (x, -count);
  966. }
  967. public static IntNum shift (IntNum x, int count)
  968. {
  969. if (x.words == null)
  970. {
  971. if (count <= 0)
  972. return make (count > -32 ? x.ival >> (-count) : x.ival < 0 ? -1 : 0);
  973. if (count < 32)
  974. return make ((long) x.ival << count);
  975. }
  976. if (count == 0)
  977. return x;
  978. IntNum result = new IntNum (0);
  979. result.setShift (x, count);
  980. return result.canonicalize ();
  981. }
  982. /* #ifdef JAVA5 */
  983. public void format (int radix, StringBuffer buffer)
  984. {
  985. if (radix == 10)
  986. {
  987. if (words == null)
  988. {
  989. buffer.append(ival);
  990. return;
  991. }
  992. else if (ival <= 2)
  993. {
  994. buffer.append(longValue());
  995. return;
  996. }
  997. }
  998. buffer.append(toString(radix));
  999. }
  1000. /* #endif */
  1001. public void format (int radix,
  1002. /* #ifdef JAVA5 */
  1003. StringBuilder buffer
  1004. /* #else */
  1005. // StringBuffer buffer
  1006. /* #endif */
  1007. )
  1008. {
  1009. if (words == null)
  1010. {
  1011. if (radix == 10)
  1012. buffer.append(ival);
  1013. else
  1014. buffer.append(Integer.toString (ival, radix));
  1015. }
  1016. else if (ival <= 2)
  1017. {
  1018. long lval = longValue();
  1019. if (radix == 10)
  1020. buffer.append(lval);
  1021. else
  1022. buffer.append(Long.toString (lval, radix));
  1023. }
  1024. else
  1025. {
  1026. boolean neg = isNegative ();
  1027. int[] work;
  1028. if (neg || radix != 16)
  1029. {
  1030. work = new int[ival];
  1031. getAbsolute (work);
  1032. }
  1033. else
  1034. work = words;
  1035. int len = ival;
  1036. if (radix == 16)
  1037. {
  1038. if (neg)
  1039. buffer.append ('-');
  1040. int buf_start = buffer.length ();
  1041. for (int i = len; --i >= 0; )
  1042. {
  1043. int word = work[i];
  1044. for (int j = 8; --j >= 0; )
  1045. {
  1046. int hex_digit = (word >> (4 * j)) & 0xF;
  1047. // Suppress leading zeros:
  1048. if (hex_digit > 0 || buffer.length () > buf_start)
  1049. buffer.append (Character.forDigit (hex_digit, 16));
  1050. }
  1051. }
  1052. }
  1053. else
  1054. {
  1055. int chars_per_word = MPN.chars_per_word(radix);
  1056. int wradix = radix;
  1057. for (int j = chars_per_word; --j > 0; )
  1058. wradix = wradix * radix;
  1059. int i = buffer.length();
  1060. for (;;)
  1061. {
  1062. int wdigit = MPN.divmod_1(work, work, len, wradix);
  1063. while (len > 0 && work[len-1] == 0) len--;
  1064. for (int j = chars_per_word; --j >= 0; ) {
  1065. int digit;
  1066. if (len == 0 && wdigit == 0)
  1067. break;
  1068. if (wdigit < 0) // Overflow
  1069. {
  1070. long ldigit = (long) wdigit & 0xFFFFFFFF;
  1071. digit = (int)(ldigit % radix);
  1072. wdigit = (int) (wdigit / radix);
  1073. }
  1074. else
  1075. {
  1076. digit = wdigit % radix;
  1077. wdigit = wdigit / radix;
  1078. }
  1079. buffer.append (Character.forDigit(digit, radix));
  1080. }
  1081. if (len == 0)
  1082. break;
  1083. }
  1084. if (neg)
  1085. buffer.append ('-');
  1086. /* Reverse buffer. */
  1087. int j = buffer.length () - 1;
  1088. while (i < j)
  1089. {
  1090. char tmp = buffer.charAt (i);
  1091. buffer.setCharAt (i, buffer.charAt (j));
  1092. buffer.setCharAt (j, tmp);
  1093. i++; j--;
  1094. }
  1095. }
  1096. }
  1097. }
  1098. public String toString (int radix)
  1099. {
  1100. if (words == null)
  1101. return Integer.toString (ival, radix);
  1102. else if (ival <= 2)
  1103. return Long.toString (longValue (), radix);
  1104. int buf_size = ival * (MPN.chars_per_word (radix) + 1);
  1105. /* #ifdef JAVA5 */
  1106. StringBuilder buffer = new StringBuilder (buf_size);
  1107. /* #else */
  1108. // StringBuffer buffer = new StringBuffer (buf_size);
  1109. /* #endif */
  1110. format(radix, buffer);
  1111. return buffer.toString ();
  1112. }
  1113. public int intValue ()
  1114. {
  1115. if (words == null)
  1116. return ival;
  1117. return words[0];
  1118. }
  1119. /** Cast an Object to an int. The Object must (currently) be an IntNum. */
  1120. public static int intValue (Object obj)
  1121. {
  1122. IntNum inum = (IntNum) obj;
  1123. if (inum.words != null)
  1124. // This is not quite appropriate, but will do.
  1125. throw new ClassCastException ("integer too large");
  1126. return inum.ival;
  1127. }
  1128. public long longValue ()
  1129. {
  1130. if (words == null)
  1131. return ival;
  1132. if (ival == 1)
  1133. return words[0];
  1134. return ((long)words[1] << 32) + ((long)words[0] & 0xffffffffL);
  1135. }
  1136. public int hashCode ()
  1137. {
  1138. return words == null ? ival : (words[0] + words[ival-1]);
  1139. }
  1140. /* Assumes x and y are both canonicalized. */
  1141. public static boolean equals (IntNum x, IntNum y)
  1142. {
  1143. if (x.words == null && y.words == null)
  1144. return x.ival == y.ival;
  1145. if (x.words == null || y.words == null || x.ival != y.ival)
  1146. return false;
  1147. for (int i = x.ival; --i >= 0; )
  1148. {
  1149. if (x.words[i] != y.words[i])
  1150. return false;
  1151. }
  1152. return true;
  1153. }
  1154. /* Assumes this and obj are both canonicalized. */
  1155. public boolean equals (Object obj)
  1156. {
  1157. if (obj == null || ! (obj instanceof IntNum))
  1158. return false;
  1159. return IntNum.equals (this, (IntNum) obj);
  1160. }
  1161. /** Return a (possibly-shared) IntNum with a given int value. */
  1162. public static IntNum make (int value) { return valueOf(value); }
  1163. /** Make an IntNum from an unsigned 64-bit value. */
  1164. public static IntNum valueOfUnsigned(long value) {
  1165. if (value >= 0)
  1166. return valueOf(value);
  1167. IntNum result = alloc(3);
  1168. result.ival = 3;
  1169. result.words[0] = (int) value;
  1170. result.words[1] = (int) (value >> 32);
  1171. result.words[2] = 0;
  1172. return result;
  1173. }
  1174. /** Make an IntNum from an unsigned 32-bit value. */
  1175. public static IntNum valueOfUnsigned(int value) {
  1176. if (value >= 0)
  1177. return valueOf(value);
  1178. IntNum result = alloc(2);
  1179. result.ival = 2;
  1180. result.words[0] = value;
  1181. result.words[1] = 0;
  1182. return result;
  1183. }
  1184. /** Make a canonicalized IntNum from an array of words.
  1185. * The array may be reused (without copying). */
  1186. public static IntNum make (int[] words, int len)
  1187. {
  1188. if (words == null)
  1189. return make (len);
  1190. len = IntNum.wordsNeeded (words, len);
  1191. if (len <= 1)
  1192. return len == 0 ? zero () : make (words[0]);
  1193. IntNum num = new IntNum ();
  1194. num.words = words;
  1195. num.ival = len;
  1196. return num;
  1197. }
  1198. public static IntNum make(int[] words) {
  1199. return make(words, words.length);
  1200. }
  1201. public static IntNum make(long value) {
  1202. return valueOf(value);
  1203. }
  1204. /** Return a (possibly-shared) IntNum with a given int value. */
  1205. public static IntNum valueOf(int value) {
  1206. if (value >= minFixNum && value <= maxFixNum)
  1207. return smallFixNums[(int) value - minFixNum];
  1208. else
  1209. return new IntNum(value);
  1210. }
  1211. /** Return a (possibly-shared) IntNum with a given long value. */
  1212. public static IntNum valueOf(long value) {
  1213. if (value >= minFixNum && value <= maxFixNum)
  1214. return smallFixNums[(int)value - minFixNum];
  1215. int i = (int) value;
  1216. if ((long)i == value)
  1217. return new IntNum (i);
  1218. IntNum result = alloc (2);
  1219. result.ival = 2;
  1220. result.words[0] = i;
  1221. result.words[1] = (int) (value >> 32);
  1222. return result;
  1223. }
  1224. public static IntNum valueOf (char[] buf, int offset, int length,
  1225. int radix, boolean negative)
  1226. {
  1227. int byte_len = 0;
  1228. byte[] bytes = new byte[length];
  1229. for (int i = 0; i < length; i++)
  1230. {
  1231. char ch = buf[offset + i];
  1232. if (ch == '-')
  1233. negative = true;
  1234. else if (ch == '_' || (byte_len == 0 && (ch == ' ' || ch == '\t')))
  1235. continue;
  1236. else
  1237. {
  1238. int digit = Character.digit(ch, radix);
  1239. if (digit < 0)
  1240. break;
  1241. bytes[byte_len++] = (byte) digit;
  1242. }
  1243. }
  1244. return valueOf (bytes, byte_len, negative, radix);
  1245. }
  1246. public static IntNum valueOf (String s, int radix)
  1247. throws NumberFormatException
  1248. {
  1249. int len = s.length ();
  1250. // Testing (len < 2 * MPN.chars_per_word(radix)) would be more accurate,
  1251. // but slightly more expensive, for little practical gain.
  1252. if (len + radix <= 28)
  1253. {
  1254. /* #ifndef JAVA7 */
  1255. // if (len > 1 && s.charAt(0) == '+'
  1256. // && Character.digit(s.charAt(1), radix) >= 0)
  1257. // s = s.substring(1);
  1258. /* #endif */
  1259. return IntNum.make (Long.parseLong (s, radix));
  1260. }
  1261. int byte_len = 0;
  1262. byte[] bytes = new byte[len];
  1263. boolean negative = false;
  1264. for (int i = 0; i < len; i++)
  1265. {
  1266. char ch = s.charAt (i);
  1267. if (ch == '-' && i == 0)
  1268. negative = true;
  1269. else if (ch == '+' && i == 0)
  1270. ; // ignore
  1271. else if (ch == '_' || (byte_len == 0 && (ch == ' ' || ch == '\t')))
  1272. continue;
  1273. else
  1274. {
  1275. int digit = Character.digit (ch, radix);
  1276. if (digit < 0)
  1277. throw new NumberFormatException("For input string: \""+s+'"');
  1278. bytes[byte_len++] = (byte) digit;
  1279. }
  1280. }
  1281. return valueOf (bytes, byte_len, negative, radix);
  1282. }
  1283. public static IntNum valueOf (byte[] digits, int byte_len,
  1284. boolean negative, int radix)
  1285. {
  1286. int chars_per_word = MPN.chars_per_word(radix);
  1287. int[] words = new int[byte_len / chars_per_word + 1];
  1288. int size = MPN.set_str(words, digits, byte_len, radix);
  1289. if (size == 0)
  1290. return zero();
  1291. if (words[size-1] < 0)
  1292. words[size++] = 0;
  1293. if (negative)
  1294. negate (words, words, size);
  1295. return make (words, size);
  1296. }
  1297. public static IntNum valueOf (String s)
  1298. throws NumberFormatException
  1299. {
  1300. return IntNum.valueOf (s, 10);
  1301. }
  1302. public double doubleValue ()
  1303. {
  1304. if (words == null)
  1305. return (double) ival;
  1306. if (ival <= 2)
  1307. return (double) longValue ();
  1308. if (isNegative ())
  1309. return IntNum.neg (this).roundToDouble (0, true, false);
  1310. else
  1311. return roundToDouble (0, false, false);
  1312. }
  1313. /** Return true if any of the lowest n bits are one.
  1314. * (false if n is negative). */
  1315. boolean checkBits (int n)
  1316. {
  1317. if (n <= 0)
  1318. return false;
  1319. if (words == null)
  1320. return n > 31 || ((ival & ((1 << n) - 1)) != 0);
  1321. int i;
  1322. for (i = 0; i < (n >> 5) ; i++)
  1323. if (words[i] != 0)
  1324. return true;
  1325. return (n & 31) != 0 && (words[i] & ((1 << (n & 31)) - 1)) != 0;
  1326. }
  1327. /** Convert a semi-processed IntNum to double.
  1328. * Number must be non-negative. Multiplies by a power of two, applies sign,
  1329. * and converts to double, with the usual java rounding.
  1330. * @param exp power of two, positive or negative, by which to multiply
  1331. * @param neg true if negative
  1332. * @param remainder true if the IntNum is the result of a truncating
  1333. * division that had non-zero remainder. To ensure proper rounding in
  1334. * this case, the IntNum must have at least 54 bits. */
  1335. public double roundToDouble (int exp, boolean neg, boolean remainder)
  1336. {
  1337. // Compute length.
  1338. int il = intLength();
  1339. // Exponent when normalized to have decimal point directly after
  1340. // leading one. This is stored excess 1023 in the exponent bit field.
  1341. exp += il - 1;
  1342. // Gross underflow. If exp == -1075, we let the rounding
  1343. // computation determine whether it is minval or 0 (which are just
  1344. // 0x0000 0000 0000 0001 and 0x0000 0000 0000 0000 as bit
  1345. // patterns).
  1346. if (exp < -1075)
  1347. return neg ? -0.0 : 0.0;
  1348. // gross overflow
  1349. if (exp > 1023)
  1350. return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1351. // number of bits in mantissa, including the leading one.
  1352. // 53 unless it's denormalized
  1353. int ml = (exp >= -1022 ? 53 : 53 + exp + 1022);
  1354. // Get top ml + 1 bits. The extra one is for rounding.
  1355. long m;
  1356. int excess_bits = il - (ml + 1);
  1357. if (excess_bits > 0)
  1358. m = ((words == null) ? ival >> excess_bits
  1359. : MPN.rshift_long (words, ival, excess_bits));
  1360. else
  1361. m = longValue () << (- excess_bits);
  1362. // Special rounding for maxval. If the number exceeds maxval by
  1363. // any amount, even if it's less than half a step, it overflows.
  1364. if (exp == 1023 && ((m >> 1) == (1L << 53) - 1))
  1365. {
  1366. if (remainder || checkBits (il - ml))
  1367. return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1368. else
  1369. return neg ? - Double.MAX_VALUE : Double.MAX_VALUE;
  1370. }
  1371. // Normal round-to-even rule: round up if the bit dropped is a one, and
  1372. // the bit above it or any of the bits below it is a one.
  1373. if ((m & 1) == 1
  1374. && ((m & 2) == 2 || remainder || checkBits (excess_bits)))
  1375. {
  1376. m += 2;
  1377. // Check if we overflowed the mantissa
  1378. if ((m & (1L << 54)) != 0)
  1379. {
  1380. exp++;
  1381. // renormalize
  1382. m >>= 1;
  1383. }
  1384. // Check if a denormalized mantissa was just rounded up to a
  1385. // normalized one.
  1386. else if (ml == 52 && (m & (1L << 53)) != 0)
  1387. exp++;
  1388. }
  1389. // Discard the rounding bit
  1390. m >>= 1;
  1391. long bits_sign = neg ? (1L << 63) : 0;
  1392. exp += 1023;
  1393. long bits_exp = (exp <= 0) ? 0 : ((long)exp) << 52;
  1394. long bits_mant = m & ~(1L << 52);
  1395. return Double.longBitsToDouble (bits_sign | bits_exp | bits_mant);
  1396. }
  1397. public Numeric add (Object y, int k)
  1398. {
  1399. if (y instanceof IntNum)
  1400. return IntNum.add (this, (IntNum) y, k);
  1401. if (!(y instanceof Numeric))
  1402. throw new IllegalArgumentException ();
  1403. return ((Numeric)y).addReversed (this, k);
  1404. }
  1405. public Numeric mul (Object y)
  1406. {
  1407. if (y instanceof IntNum)
  1408. return IntNum.times (this, (IntNum) y);
  1409. if (!(y instanceof Numeric))
  1410. throw new IllegalArgumentException ();
  1411. return ((Numeric)y).mulReversed (this);
  1412. }
  1413. public Numeric div (Object y)
  1414. {
  1415. if (y instanceof RatNum)
  1416. {
  1417. RatNum r = (RatNum) y;
  1418. return RatNum.make (IntNum.times (this, r.denominator()),
  1419. r.numerator());
  1420. }
  1421. if (! (y instanceof Numeric))
  1422. throw new IllegalArgumentException ();
  1423. return ((Numeric)y).divReversed (this);
  1424. }
  1425. /** Copy the abolute value of this into an array of words.
  1426. * Assumes {@code words.length >= (this.words == null ? 1 : this.ival)}.
  1427. * Result is zero-extended, but need not be a valid 2's complement number.
  1428. */
  1429. public void getAbsolute (int[] words)
  1430. {
  1431. int len;
  1432. if (this.words == null)
  1433. {
  1434. len = 1;
  1435. words[0] = this.ival;
  1436. }
  1437. else
  1438. {
  1439. len = this.ival;
  1440. for (int i = len; --i >= 0; )
  1441. words[i] = this.words[i];
  1442. }
  1443. if (words[len-1] < 0)
  1444. negate (words, words, len);
  1445. for (int i = words.length; --i > len; )
  1446. words[i] = 0;
  1447. }
  1448. /** Set dest[0:len-1] to the negation of src[0:len-1].
  1449. * Return true if overflow (i.e. if src is -2**(32*len-1)).
  1450. * Ok for src==dest. */
  1451. public static boolean negate (int[] dest, int[] src, int len)
  1452. {
  1453. long carry = 1;
  1454. boolean negative = src[len-1] < 0;
  1455. for (int i = 0; i < len; i++)
  1456. {
  1457. carry += ((long) (~src[i]) & 0xffffffffL);
  1458. dest[i] = (int) carry;
  1459. carry >>= 32;
  1460. }
  1461. return (negative && dest[len-1] < 0);
  1462. }
  1463. /** Destructively set this to the negative of x.
  1464. * It is OK if x==this.*/
  1465. public void setNegative (IntNum x)
  1466. {
  1467. int len = x.ival;
  1468. if (x.words == null)
  1469. {
  1470. if (len == Integer.MIN_VALUE)
  1471. set (- (long) len);
  1472. else
  1473. set (-len);
  1474. return;
  1475. }
  1476. realloc (len + 1);
  1477. if (IntNum.negate (words, x.words, len))
  1478. words[len++] = 0;
  1479. ival = len;
  1480. }
  1481. /** Destructively negate this. */
  1482. public final void setNegative ()
  1483. {
  1484. setNegative (this);
  1485. }
  1486. public static IntNum abs (IntNum x)
  1487. {
  1488. return x.isNegative () ? neg (x) : x;
  1489. }
  1490. public static IntNum neg (IntNum x)
  1491. {
  1492. if (x.words == null && x.ival != Integer.MIN_VALUE)
  1493. return make (- x.ival);
  1494. IntNum result = new IntNum (0);
  1495. result.setNegative (x);
  1496. return result.canonicalize ();
  1497. }
  1498. public Numeric neg ()
  1499. {
  1500. return IntNum.neg (this);
  1501. }
  1502. /** Calculates {@code ceiling(log2(this < 0 ? -this : this+1))}.
  1503. * See Common Lisp: the Language, 2nd ed, p. 361.
  1504. */
  1505. public int intLength ()
  1506. {
  1507. if (words == null)
  1508. return MPN.intLength (ival);
  1509. else
  1510. return MPN.intLength (words, ival);
  1511. }
  1512. /**
  1513. * @serialData If the value is in the range (int)0xC0000000 .. 0x7fffffff
  1514. * (inclusive) write out the value (using writeInt).
  1515. * Otherwise, write (using writeInt) (0x80000000|nwords), where nwords is
  1516. * the number of words following. The words are the minimal
  1517. * 2's complement big-endian representation of the value, written using
  1518. * writeint.
  1519. * (Even if the current value is not canonicalized, the output is).
  1520. */
  1521. public void writeExternal(ObjectOutput out) throws IOException
  1522. {
  1523. int nwords = words == null ? 1 : wordsNeeded(words, ival);
  1524. if (nwords <= 1)
  1525. {
  1526. int i = words == null ? ival : words.length == 0 ? 0 : words[0];
  1527. if (i >= (int)0xC0000000)
  1528. out.writeInt(i);
  1529. else
  1530. {
  1531. out.writeInt(0x80000001);
  1532. out.writeInt(i);
  1533. }
  1534. }
  1535. else
  1536. {
  1537. out.writeInt(0x80000000|nwords);
  1538. while (--nwords >= 0)
  1539. out.writeInt(words[nwords]);
  1540. }
  1541. }
  1542. public void readExternal(ObjectInput in)
  1543. throws IOException, ClassNotFoundException
  1544. {
  1545. int i = in.readInt();
  1546. if (i <= (int) 0xC0000000)
  1547. {
  1548. i &= 0x7fffffff;
  1549. if (i == 1)
  1550. i = in.readInt();
  1551. else
  1552. {
  1553. int[] w = new int[i];
  1554. for (int j = i; --j >= 0; )
  1555. w[j] = in.readInt();
  1556. words = w;
  1557. }
  1558. }
  1559. ival = i;
  1560. }
  1561. public Object readResolve() throws ObjectStreamException
  1562. {
  1563. return canonicalize();
  1564. }
  1565. public BigInteger asBigInteger ()
  1566. {
  1567. if (words == null || ival <= 2)
  1568. return BigInteger.valueOf(longValue());
  1569. return new BigInteger(toString());
  1570. }
  1571. public BigDecimal asBigDecimal ()
  1572. {
  1573. if (words == null)
  1574. return new BigDecimal(ival);
  1575. if (ival <= 2)
  1576. return BigDecimal.valueOf(longValue());
  1577. return new BigDecimal(toString());
  1578. }
  1579. /** Is this integer both {@code >= lo} and {@code <= hi}?. */
  1580. public boolean inRange (long lo, long hi)
  1581. {
  1582. return compare(this, lo) >= 0 && compare(this, hi) <= 0;
  1583. }
  1584. /** Does this value fit in a signed 32-bit {@code int}? */
  1585. public boolean inIntRange ()
  1586. {
  1587. return inRange(Integer.MIN_VALUE, Integer.MAX_VALUE);
  1588. }
  1589. /** Does this value fit in a signed 64-bit {@code long}? */
  1590. public boolean inLongRange ()
  1591. {
  1592. return inRange(Long.MIN_VALUE, Long.MAX_VALUE);
  1593. }
  1594. }