summaryrefslogtreecommitdiff
path: root/big.c
blob: 24a4cc6f98cdc789e7e2ddf8e1121b366fdfe35f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
/* MIRANDA INTEGER PACKAGE */
/* package for unbounded precision integers */

/**************************************************************************
 * Copyright (C) Research Software Limited 1985-90.  All rights reserved. *
 * The Miranda system is distributed as free software under the terms in  *
 * the file "COPYING" which is included in the distribution.              *
 *                                                                        *
 * Revised to C11 standard and made 64bit compatible, January 2020        *
 *------------------------------------------------------------------------*/

#include "data.h"
#include "lex.h"
#include "big.h"
#include <errno.h>

#define MAX_INT_BITS		60
#define LONG_LONG_OVERFLOW	(1ll<<MAX_INT_BITS)

word big_one;

static word big_plus(word, word, int);
static word big_sub(word, word);
static word len(word);
static word longdiv(word, word);
static word ms2d(word);
static word msd(word);
static word shift(word, word);
static word shortdiv(word, word);
static word stimes(word, word);

void bigsetup(void)
{
  big_one = make(INT, 1, 0);
}

int isnat(word x)
{
  return (tag[x] == INT && big_is_positive(x));
}

/* store C long long as mira bigint */
word sto_int(long long i)
{
  word sign = 0;

  if (i < 0) {
    sign = SIGNBIT;
    i = -i;
  }

  word x = make(INT, (sign | i) & MAXDIGIT, 0);
  if (i >>= DIGITWIDTH) {
    word *p = &rest(x);
    do {
      *p = make(INT, i & MAXDIGIT, 0);
      p = &rest(*p);
    } while (i >>= DIGITWIDTH);
  }

  return x;
}

/* mira bigint to C long long */
long long get_int(word x)
{
  long long n = digit0(x);
  word sign = big_is_negative(x);
  if (!(x = rest(x))) {
    return (sign ? -n : n);
  }

  word w = DIGITWIDTH;
  while (x && w < MAX_INT_BITS) {
    n += (long long)digit(x) << w;
    w += DIGITWIDTH;
    x = rest(x);
  }

  if (x) {
    n = LONG_LONG_OVERFLOW;
  }

  return (sign ? -n : n);
}

word bignegate(word x)
{
  if (bigzero(x)) {
    return x;
  }

  if (hd[x] & SIGNBIT) {
    return make(INT, hd[x] & MAXDIGIT, tl[x]);
  }
  return make(INT, SIGNBIT | hd[x], tl[x]);
}

word bigplus(word x, word y)
{
  if (big_is_positive(x)) {
    if (big_is_positive(y)) {
      return (big_plus(x, y, 0));
    }
    return (big_sub(x, y));
  }

  if (big_is_positive(y)) {
    return (big_sub(y, x));
  }

  return (big_plus(x, y, SIGNBIT));	/* both negative */
}

/* ignore input signs, treat x,y as positive */
word big_plus(word x, word y, int signbit)
{
  word d = digit0(x) + digit0(y);
  word r = make(INT, signbit | d & MAXDIGIT, 0);	/* result */
  word *z = &rest(r);		/* pointer to rest of result */

  word carry = ((d & IBASE) != 0);
  x = rest(x);
  y = rest(y);

  while (x && y) {
    d = carry + digit(x) + digit(y);
    carry = ((d & IBASE) != 0);
    *z = make(INT, d & MAXDIGIT, 0);
    x = rest(x);
    y = rest(y);
    z = &rest(*z);
  }

  if (y) {
    x = y;			/* by convention x is the longer one */
  }

  while (x) {
    d = carry + digit(x);
    carry = ((d & IBASE) != 0);
    *z = make(INT, d & MAXDIGIT, 0);
    x = rest(x);
    z = &rest(*z);
  }

  if (carry) {
    *z = make(INT, 1, 0);
  }

  return r;
}

word bigsub(word x, word y)
{
  if (big_is_positive(x)) {
    if (big_is_positive(y)) {
      return (big_sub(x, y));		/* both positive */
    }
    return (big_plus(x, y, 0));		/* positive x, negative y */
  }

  if (big_is_positive(y)) {
    return (big_plus(x, y, SIGNBIT));	/* negative x, positive y */
  }

  return (big_sub(y, x));	/* both negative */
}

/* ignore input signs, treat x,y as positive */
word big_sub(word x, word y)
{
  word d = digit0(x) - digit0(y);
  word borrow = (d & IBASE) != 0;
  word r = make(INT, d & MAXDIGIT, 0);	/* result */
  word *z = &rest(r);
  word *p = NULL;		/* pointer to trailing zeros, if any */
  x = rest(x);
  y = rest(y);

  /* this loop has been unwrapped once, see above */
  while (x && y) {
    d = digit(x) - digit(y) - borrow;
    borrow = (d & IBASE) != 0;
    d = d & MAXDIGIT;
    *z = make(INT, d, 0);

    if (d) {
      p = NULL;
    } else if (!p) {
      p = z;
    }

    x = rest(x);
    y = rest(y);
    z = &rest(*z);
  }

  /* at most one of these two loops will be invoked */
  while (y) {
    d = -digit(y) - borrow;
    borrow = ((d & IBASE) != 0);
    d = d & MAXDIGIT;
    *z = make(INT, d, 0);

    if (d) {
      p = NULL;
    } else if (!p) {
      p = z;
    }

    y = rest(y);
    z = &rest(*z);
  }

  /* alternative loop */
  while (x) {
    d = digit(x) - borrow;
    borrow = ((d & IBASE) != 0);
    d = d & MAXDIGIT;
    *z = make(INT, d, 0);

    if (d) {
      p = NULL;
    } else if (!p) {
      p = z;
    }

    x = rest(x);
    z = &rest(*z);
  }

  /* result is negative  - take complement and add 1 */
  if (borrow) {
    p = NULL;
    d = (digit(r) ^ MAXDIGIT) + 1;
    borrow = ((d & IBASE) != 0);	/* borrow now means `carry' (sorry) */
    digit(r) = SIGNBIT | d;	/* set sign bit of result */
    z = &rest(r);

    while (*z) {
      d = (digit(*z) ^ MAXDIGIT) + borrow;
      borrow = ((d & IBASE) != 0);
      digit(*z) = d = d & MAXDIGIT;

      if (d) {
	p = NULL;
      } else if (!p) {
	p = z;
      }

      z = &rest(*z);
    }
  }

  /* remove redundant (ie trailing) zeros */
  if (p) {
    *p = 0;
  }

  return r;
}

/* returns +ve,0,-ve as x greater than, equal, less than y */
int bigcmp(word x, word y)
{
  word s = big_is_negative(x);
  if (big_is_negative(y) != s) {
    return (s ? -1 : 1);
  }

  word r = digit0(x) - digit0(y);
  for (;;) {
    x = rest(x);
    y = rest(y);

    if (!x) {
      if (y) {
	return (s ? 1 : -1);
      }
      return (s ? -r : r);
    }

    if (!y) {
      return (s ? -1 : 1);
    }

    word d = digit(x) - digit(y);
    if (d) {
      r = d;
    }
  }
}

/* naive multiply - quadratic */
word bigtimes(word x, word y)
{
  /* important optimisation */
  if (len(x) < len(y)) {
    word hold = x;
    x = y;
    y = hold;
  }

  word r = make(INT, 0, 0);

  /* short cut */
  if (bigzero(x)) {
    return (r);
  }

  word s = big_is_negative(y);
  for (word n = 0, d = digit0(y); y; n++, d = digit(y)) {
    if (d) {
      r = bigplus(r, shift(n, stimes(x, d)));
    }

    y = rest(y);
  }
  return (s != big_is_negative(x) ? bignegate(r) : r);
}

/* multiply big x by n'th power of IBASE */
word shift(word n, word x)
{
  while (n--) {
    x = make(INT, 0, x);
  }

  return x;
}

/* multiply big x (>=0) by digit n (>0) */
word stimes(word x, word n)
{
  unsigned d = n * digit0(x);	/* ignore sign of x */
  word carry = d >> DIGITWIDTH;
  word r = make(INT, d & MAXDIGIT, 0);
  word *y = &rest(r);

  while (x = rest(x)) {
    d = n * digit(x) + carry;
    *y = make(INT, d & MAXDIGIT, 0);
    y = &rest(*y);
    carry = d >> DIGITWIDTH;
  }

  if (carry) {
    *y = make(INT, carry, 0);
  }

  return r;
}

/* TODO: make bigdiv()/bigmod() behave like div()/ldiv()/lldiv() */
word b_rem;			/* contains remainder from last call to longdiv or shortdiv */

/* may assume y~=0 */
word bigdiv(word x, word y)
{
  word s1 = big_is_negative(y);
  word s2 = s1;

  /* make x,y positive and remember signs */
  if (s1) {
    y = make(INT, digit0(y), rest(y));
  }

  /* effect: s1 set iff y negative, s2 set iff signs mixed */
  if (big_is_negative(x)) {
    x = make(INT, digit0(x), rest(x));
    s2 = !s1;
  }

  word q = rest(y) ? longdiv(x, y) : shortdiv(x, digit(y));

  if (s2) {
    if (!bigzero(b_rem)) {
      x = q;
      while ((digit(x) += 1) == IBASE) {	/* add 1 to q in situ */
	digit(x) = 0;
	if (!rest(x)) {
	  rest(x) = make(INT, 1, 0);
	  break;
	}
        x = rest(x);
      }
    }
    if (!bigzero(q)) {
      digit(q) = SIGNBIT | digit(q);
    }
  }

  return q;
}

/* may assume y~=0 */
word bigmod(word x, word y)
{
  word s1 = big_is_negative(y);
  word s2 = s1;

  /* make x,y positive and remember signs */
  if (s1) {
    y = make(INT, digit0(y), rest(y));
  }

  if (big_is_negative(x)) {
    x = make(INT, digit0(x), rest(x));
    s2 = !s1;
  }

  /* effect: s1 set iff y negative, s2 set iff signs mixed */
  if (rest(y)) {
    longdiv(x, y);
  } else {
    shortdiv(x, digit(y));
  }

  if (s2) {
    if (!bigzero(b_rem)) {
      b_rem = bigsub(y, b_rem);
    }
  }
  return (s1 ? bignegate(b_rem) : b_rem);
}

/* NB - above have entier based handling of signed cases  (as  Miranda)  in
   which  remainder  has  sign  of  divisor.   To  get  this:-  if signs of
   divi(sor/dend) mixed negate quotient  and  if  remainder  non-zero  take
   complement and add one to magnitude of quotient */

/* for alternative, truncate based handling of signed cases (usual in  C):-
   magnitudes  invariant  under  change  of  sign,  remainder  has  sign of
   dividend, quotient negative if signs of divi(sor/dend) mixed */

/* divide big x by single digit n returning big quotient
   and setting external b_rem as side effect */
/* may assume - x>=0,n>0 */
word shortdiv(word x, word n)
{
  word d = digit(x);
  word q = 0;

  /* reverse rest(x) into q */
  while (x = rest(x)) {
    q = make(INT, d, q);
    d = digit(x);	/* leaving most sig. digit in d */
  }

  x = q;
  word s_rem = d % n;
  d = d / n;

  /* put back first digit (if not leading 0) */
  if (d || !q) {
    q = make(INT, d, 0);
  } else {
    q = 0;
  }

  /* in situ division of q by n AND destructive reversal */
  while (x) {
    d = s_rem * IBASE + digit(x);
    digit(x) = d / n;
    s_rem = d % n;
    word tmp = x;
    x = rest(x);
    rest(tmp) = q;
    q = tmp;
  }

  b_rem = make(INT, s_rem, 0);
  return q;
}

/* divide big x by big y returning quotient, leaving
   remainder in extern variable b_rem */
/* may assume - x>=0,y>0 */
word longdiv(word x, word y)
{
  if (bigcmp(x, y) < 0) {
    b_rem = x;
    return (make(INT, 0, 0));
  }

  word y1 = msd(y);

  /* rescale if necessary */
  word scale = IBASE / (y1 + 1);
  if (scale > 1) {
    x = stimes(x, scale);
    y = stimes(y, scale);
    y1 = msd(y);
  }

  word n = 0;
  word q = 0;
  word ly = len(y);
  while (bigcmp(x, y = make(INT, 0, y)) >= 0) {
    n++;
  }

  y = rest(y);			/* want largest y not exceeding x */
  ly += n;
  for (;;) {
    word d, lx = len(x);
    if (lx < ly) {
      d = 0;

    } else if (lx == ly) {
      if (bigcmp(x, y) >= 0) {
	x = bigsub(x, y);
        d = 1;
      } else {
	d = 0;
      }

    } else {
      d = ms2d(x) / y1;
      if (d > MAXDIGIT) {
	d = MAXDIGIT;
      }

      if ((d -= 2) > 0) {
	x = bigsub(x, stimes(y, d));
      } else {
	d = 0;
      }

      if (bigcmp(x, y) >= 0) {
	x = bigsub(x, y), d++;
	if (bigcmp(x, y) >= 0) {
	  x = bigsub(x, y);
          d++;
        }
      }
    }

    q = make(INT, d, q);
    if (n-- == 0) {
      b_rem = scale == 1 ? x : shortdiv(x, scale);
      return (q);
    }
    ly--;
    y = rest(y);
  }
}				/* see Bird & Wadler p82 for explanation */

/* no of digits in big x */
word len(word x)
{
  word n = 1;
  while (x = rest(x)) {
    n++;
  }

  return n;
}

/* most significant digit of big x */
word msd(word x)
{
  while (rest(x)) {
    x = rest(x);
  }

  return digit(x);		/* sign? */
}

/* most significant 2 digits of big x (len>=2) */
word ms2d(word x)
{
  word d = digit(x);
  x = rest(x);
  while (rest(x)) {
    d = digit(x);
    x = rest(x);
  }

  return (digit(x) * IBASE + d);
}

/* assumes y big_is_positive */
word bigpow(word x, word y)
{
  word d;
  word r = make(INT, 1, 0);

  /* this loop has been unwrapped once, see below */
  while (rest(y)) {	
    word i = DIGITWIDTH;
    d = digit(y);
    while (i--) {
      if (d & 1) {
	r = bigtimes(r, x);
      }
      x = bigtimes(x, x);
      d >>= 1;
    }
    y = rest(y);
  }

  d = digit(y);
  if (d & 1) {
    r = bigtimes(r, x);
  }

  while (d >>= 1) {
    x = bigtimes(x, x);
    if (d & 1) {
      r = bigtimes(r, x);
    }
  }

  return r;
}

double bigtodbl(word x)
{
  word s = big_is_negative(x);
  double b = 1.0;
  double r = (double)digit0(x);
  x = rest(x);
  while (x) {
    b = b * IBASE;
    r = r + b * digit(x);
    x = rest(x);
  }

  return s ? -r : r;
}				/* small end first */

/* note: can return oo, -oo
   but is used without surrounding sto_/set)dbl() only in compare() */

/* entier */
word dbltobig(double x)
{
  word s = (x < 0);
  word r = make(INT, 0, 0);
  word *p = &r;
  double y = floor(x);

  for (y = fabs(y);;) {
    double n = fmod(y, (double)IBASE);
    digit(*p) = (word) n;
    y = (y - n) / (double)IBASE;
    if (y > 0.0) {
      rest(*p) = make(INT, 0, 0);
      p = &rest(*p);
    } else {
      break;
    }
  }

  if (s) {
    digit(r) = SIGNBIT | digit(r);
  }

  return r;
}

/* produces junk in low order digits if x exceeds range in which integer
   can be held without error as a double -- NO, see next comment */
/* hugs, ghci, mira produce same integer for floor/entier hugenum, has 2^971
   as factor so the low order bits are NOT JUNK -- 9.1.12 */

/* note on suppressed fix:
   choice of 1e9 arbitrary, chosen to prevent eg entier(100*0.29) = 28
   but has undesirable effects, causing eg entier 1.9999999999 = 2
   underlying problem is that computable floor on true Reals is _|_ at
   the exact integers.  There are inherent deficiences in 64 bit fp,
   no point in trying to mask this */

static double big__log(word x, double logbase, char *name, double (*fn)(double))
{
  word n = 0;
  double r = digit(x);

  if (big_is_negative(x) || bigzero(x)) {
    errno = EDOM;
    math_error(name);
  }

  while ((x = rest(x)) != 0) {
    n++;
    r = digit(x) + r / IBASE;
  }

  return (fn(r) + n * logbase);
}

/* logarithm of big x */
double biglog(word x)
{
  static double logIBASE = 0.0;
  if (logIBASE == 0.0) {
    logIBASE = log((double)IBASE);
  }

  return big__log(x, logIBASE, "log", log);
}

/* logarithm of big x */
double biglog10(word x)
{
  static double log10IBASE = 0.0;
  if (log10IBASE == 0.0) {
    log10IBASE = log10((double)IBASE);
  }

  return big__log(x, log10IBASE, "log10", log10);
}

/* read a big number (in decimal) */
/* NB does NOT check for malformed number, assumes already done */
/* p is a pointer to a null terminated string of digits */
word bigscan(char *p)
{
  word s = 0;
  word r = make(INT, 0, 0);

  /* optional leading `-' (for NUMVAL) */
  if (*p == '-') {
    s = 1;
    p++;
  }

  while (*p) {
    word d = *p - '0', f = 10;
    p++;

    while (*p && f < PTEN) {
      d = 10 * d + *p - '0';
      f = 10 * f;
      p++;
    }

    /* rest of loop does r=f*r+d; (in situ) */
    d = f * digit(r) + d;

    word carry = d >> DIGITWIDTH;
    word *x = &rest(r);
    digit(r) = d & MAXDIGIT;
    while (*x) {
      d = f * digit(*x) + carry;
      digit(*x) = d & MAXDIGIT;
      carry = d >> DIGITWIDTH;
      x = &rest(*x);
    }

    if (carry) {
      *x = make(INT, carry, 0);
    }
  }

  if (s && !bigzero(r)) {
    digit(r) = digit(r) | SIGNBIT;
  }

  return r;
}

/* code to handle (unsigned) exponent commented out */

/* read unsigned hex number in '\0'-terminated string p to q */
/* assumes redundant leading zeros removed */
word bigxscan(char *p, char *q)
{
  if (*p == '0' && !p[1]) {
    return make(INT, 0, 0);
  }

  word r;			/* will hold result */
  word *x = &r;

  while (q > p) {
    unsigned long long hold;
    q = q - p < 15 ? p : q - 15;	/* read upto 15 hex digits from small end */
    sscanf(q, "%llx", &hold);
    *q = '\0';
    word count = 4;		/* 15 hex digits => 4 bignum digits */
    while (count-- && !(hold == 0 && q == p)) {
      *x = make(INT, hold & MAXDIGIT, 0);
      hold >>= DIGITWIDTH;
      x = &rest(*x);
    }
  }

  return r;
}

/* read unsigned octal number in '\0'-terminated string p to q */
/* assumes redundant leading zeros removed */
word bigoscan(char *p, char *q)
{
  word r;			/* will hold result */
  word *x = &r;

  while (q > p) {
    unsigned hold;
    q = q - p < 5 ? p : q - 5;	/* read (upto) 5 octal digits from small end */
    sscanf(q, "%o", &hold);
    *q = '\0';
    *x = make(INT, hold, 0), x = &rest(*x);
  }

  return r;
}

/* TODO: this assumes ASCII/UTF-8 */
word digitval(char c)
{
  return isdigit(c) ? c - '0' : 10 + tolower(c) - 'a';
}

/* numeral (as Miranda string) to big number */
/* does NOT check for malformed numeral, assumes
   done and that z fully evaluated */
word strtobig(word z, int base)
{
  word s = 0;
  word r = make(INT, 0, 0);
 
  word PBASE = PTEN;
  if (base == 16) {
    PBASE = PSIXTEEN;
  } else if (base == 8) {
    PBASE = PEIGHT;
  }

  /* optional leading `-' (for NUMVAL) */
  if (z != NIL && hd[z] == '-') {
    s = 1;
    z = tl[z];
  }

  /* remove "0x" or "0o" */
  if (base != 10) {
    z = tl[tl[z]];
  }

  while (z != NIL) {
    word d = digitval(hd[z]);
    word f = base;
    z = tl[z];

    while (z != NIL && f < PBASE) {
      d = base * d + digitval(hd[z]);
      f = base * f;
      z = tl[z];
    }

    /* rest of loop does r=f*r+d; (in situ) */
    d = f * digit(r) + d;
    {
      word carry = d >> DIGITWIDTH;
      word *x = &rest(r);
      digit(r) = d & MAXDIGIT;

      while (*x) {
	d = f * digit(*x) + carry;
        digit(*x) = d & MAXDIGIT;
        carry = d >> DIGITWIDTH;
        x = &rest(*x);
      }

      if (carry) {
	*x = make(INT, carry, 0);
      }
    }
  }

  if (s && !bigzero(r)) {
    digit(r) = digit(r) | SIGNBIT;
  }

  return r;
}


/* number to decimal string (as Miranda list) */
word bigtostr(word x)
{
  word x1, sign, s = NIL;

#ifdef DEBUG
  extern int debug;
  if (debug & 04) {		/* print octally */
    word d = digit0(x);
    sign = big_is_negative(x);
    for (;;) {
      word i = OCTW;

      while (i-- || d) {
	s = cons('0' + (d & 07), s);
        d >>= 3;
      }

      x = rest(x);
      if (x) {
	s = cons(' ', s), d = digit(x);
      } else {
	return (sign ? cons('-', s) : s);
      }
    }
  }
#endif

  if (rest(x) == 0) {
    extern char *dicp;
    sprintf(dicp, "%ld", getsmallint(x));
    return (str_conv(dicp));
  }

  sign = big_is_negative(x);

  x1 = make(INT, digit0(x), 0);	/* reverse x into x1 */
  while (x = rest(x)) {
    x1 = make(INT, digit(x), x1);
  }
  x = x1;

  /* in situ division of (reversed order) x by PTEN */
  for (;;) {
    word d = digit(x);
    word rem = d % PTEN;
    d = d / PTEN;
    x1 = rest(x);

    if (d) {
      digit(x) = d;
    } else {
      x = x1;			/* remove leading zero from result */
    }

    while (x1) {
      d = rem * IBASE + digit(x1);
      digit(x1) = d / PTEN;
      rem = d % PTEN;
      x1 = rest(x1);
    }

    /* end of in situ division (also uses x1 as temporary) */
    if (x) {
      word i = TENW;
      while (i--) {
	s = cons('0' + rem % 10, s);
        rem = rem / 10;
      }
    } else {
      while (rem) {
	s = cons('0' + rem % 10, s);
        rem = rem / 10;
      }
      return (sign ? cons('-', s) : s);
    }
  }
}

/* integer to hexadecimal string (as Miranda list) */
word bigtostrx(word x)
{
  extern char *dicp;
  word r = NIL;
  word s = big_is_negative(x);

  while (x) {
    word count = 4;		/* 60 bits => 20 octal digits => 4 bignum digits */
    unsigned long long factor = 1;
    unsigned long long hold = 0;

    /* calculate value of (upto) 4 bignum digits */
    while (count-- && x) {
      hold = hold + factor * digit0(x);
      factor <<= 15;
      x = rest(x);
    }

    sprintf(dicp, "%.15llx", hold);	/* 15 hex digits = 60 bits */
    char *q = dicp + 15;
    while (--q >= dicp) {
      r = cons(*q, r);
    }
  }

  while (digit(r) == '0' && rest(r) != NIL) {
    r = rest(r);		/* remove redundant leading 0's */
  }

  r = cons('0', cons('x', r));

  return s ? cons('-', r) : r;
}

word bigtostr8(x)		/* integer to octal string (as Miranda list) */
word x;
{
  extern char *dicp;
  word r = NIL, s = big_is_negative(x);
  while (x) {
    char *q = dicp + 5;
    sprintf(dicp, "%.5lo", digit0(x));
    while (--q >= dicp)
      r = cons(*q, r);
    x = rest(x);
  }
  while (digit(r) == '0' && rest(r) != NIL)
    r = rest(r);		/* remove redundant leading 0's */
  r = cons('0', cons('o', r));
  if (s)
    r = cons('-', r);
  return (r);
}