-
Notifications
You must be signed in to change notification settings - Fork 0
/
bigdigits.c
2776 lines (2368 loc) · 63.7 KB
/
bigdigits.c
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
/* $Id: bigdigits.c $ */
/******************** SHORT COPYRIGHT NOTICE**************************
This source code is part of the BigDigits multiple-precision
arithmetic library Version 2.2 originally written by David Ireland,
copyright (c) 2001-8 D.I. Management Services Pty Limited, all rights
reserved. It is provided "as is" with no warranties. You may use
this software under the terms of the full copyright notice
"bigdigitsCopyright.txt" that should have been included with this
library or can be obtained from <www.di-mgt.com.au/bigdigits.html>.
This notice must always be retained in any copy.
******************* END OF COPYRIGHT NOTICE***************************/
/*
Last updated:
$Date: 2008-07-31 12:54:00 $
$Revision: 2.2.0 $
$Author: dai $
*/
/* Core code for BigDigits library "mp" functions */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include "bigdigits.h"
/* For debugging - these are NOOPs */
#define DPRINTF0(s)
#define DPRINTF1(s, a1)
/***************************************/
/* VERSION NUMBERS - USED IN MPVERSION */
/***************************************/
static const int kMajor = 2, kMinor = 2, kRelease = 0;
/* Flags for preprocessor definitions used (=last digit of mpVersion) */
#ifdef USE_SPASM
static const int kUseSpasm = 1;
#else
static const int kUseSpasm = 0;
#endif
#ifdef USE_64WITH32
static const int kUse64with32 = 2;
#else
static const int kUse64with32 = 0;
#endif
#ifdef NO_ALLOCS
static const int kUseNoAllocs = 5;
#else
static const int kUseNoAllocs = 0;
#endif
/* Useful definitions */
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
/****************************/
/* ERROR HANDLING FUNCTIONS */
/****************************/
/* Change these to suit your tastes and operating system. */
#if defined(_WIN32) || defined(WIN32)
/* Win32 GUI alternative */
#ifndef STRICT
#define STRICT
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void mpFail(char *msg)
{
MessageBox(NULL, msg, "BigDigits Error", MB_ICONERROR);
exit(EXIT_FAILURE);
}
#else /* Ordinary console program */
void mpFail(char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
#endif /* _WIN32 */
/*******************************/
/* MEMORY ALLOCATION FUNCTIONS */
/*******************************/
#ifndef NO_ALLOCS
DIGIT_T *mpAlloc(size_t ndigits)
{
DIGIT_T *ptr;
ptr = (DIGIT_T *)calloc(ndigits, sizeof(DIGIT_T));
if (!ptr)
mpFail("mpAlloc: Unable to allocate memory.");
return ptr;
}
void mpFree(DIGIT_T **p)
{
if (*p)
{
free(*p);
*p = NULL;
}
}
#endif /* NO_ALLOCS */
/* Force linker to include copyright notice in executable object image */
volatile char *copyright_notice(void)
{
return
"Contains multiple-precision arithmetic code originally written by David Ireland,"
" copyright (c) 2001-8 by D.I. Management Services Pty Limited <www.di-mgt.com.au>,"
" and is used with permission.";
}
/* To use, include this statement somewhere in the final code:
copyright_notice();
It has no real effect at run time.
Thanks to Phil Zimmerman for this idea.
*/
/****************/
/* VERSION INFO */
/****************/
int mpVersion(void)
{
return (kMajor * 1000 + kMinor * 100 + kRelease * 10 + kUseSpasm + kUse64with32 + kUseNoAllocs);
}
/**************************************/
/* CORE SINGLE PRECISION CALCULATIONS */
/* (double where necessary) */
/**************************************/
/* [v2.2] Moved these functions into main file
and added third option using 64-bit arithmetic if available.
OPTIONS:
1. define USE_64WITH32 to use 64-bit types on a 32-bit machine; or
2. define USE_SPASM to use Intel ASM (32-bit Intel compilers with __asm support); or
3. use default "long" calculations (any platform)
*/
#ifdef USE_64WITH32
/* 1. We are on a 32-bit machine with a 64-bit type available. */
#pragma message("USE_64WITH32 is set")
/* Make sure we have a uint64_t available */
#if defined (_WIN32) || defined(WIN32)
typedef unsigned __int64 uint64_t;
#elif !defined(HAVE_C99INCLUDES) && !defined(HAVE_SYS_TYPES)
typedef unsigned long long int uint64_t;
#endif
int spMultiply(uint32_t p[2], uint32_t x, uint32_t y)
{
/* Use a 64-bit temp for product */
uint64_t t = (uint64_t)x * (uint64_t)y;
/* then split into two parts */
p[1] = (uint32_t)(t >> 32);
p[0] = (uint32_t)(t & 0xFFFFFFFF);
return 0;
}
uint32_t spDivide(uint32_t *pq, uint32_t *pr, const uint32_t u[2], uint32_t v)
{
uint64_t uu, q;
uu = (uint64_t)u[1] << 32 | (uint64_t)u[0];
q = uu / (uint64_t)v;
//r = uu % (uint64_t)v;
*pr = (uint32_t)(uu - q * v);
*pq = (uint32_t)(q & 0xFFFFFFFF);
return (uint32_t)(q >> 32);
}
#elif defined(USE_SPASM)
/* Use Intel MASM to compute sp products and divisions */
#pragma message("Using MASM")
int spMultiply(uint32_t p[2], uint32_t x, uint32_t y)
/* ASM version explicitly for 32-bit integers */
{
/* Computes p = (p1p0) = x * y. No restrictions on input. */
__asm
{
mov eax, x
xor edx, edx
mul y
; Product in edx:eax
mov ebx, p
mov dword ptr [ebx], eax
mov dword ptr [ebx+4], edx
}
return 0;
}
uint32_t spDivide(uint32_t *pq, uint32_t *pr, const uint32_t u[2], uint32_t v)
/* ASM version explicitly for 32-bit integers */
{
/* Computes quotient q = u / v, remainder r = u mod v.
Returns overflow (1) if q > word size (b) otherwise returns 0.
CAUTION: Requires v >= [b/2] i.e. v to have its high bit set.
(q1q0) = (u1u0)/v0
(r0) = (u1u0) mod v0
Sets *pr = r0, *pq = q0 and returns "overflow" q1 (either 0 or 1).
*/
uint32_t overflow = 0;
__asm
{
; Dividend u in EDX:EAX, divisor in v
mov ebx, u
mov eax, dword ptr [ebx]
mov edx, dword ptr [ebx+4]
; Catch overflow (edx >= divisor)
cmp edx, v
jb no_overflow
; If so, set edx = edx - divisor and flag it
sub edx, v
mov overflow, 1
no_overflow:
div v
; Quotient in EAX, Remainder in EDX
mov ebx, pq
mov dword ptr [ebx], eax
mov ebx, pr
mov dword ptr [ebx], edx
}
return overflow;
}
#else
/* Default routines the "long" way */
int spMultiply(DIGIT_T p[2], DIGIT_T x, DIGIT_T y)
{ /* Computes p = x * y */
/* Ref: Arbitrary Precision Computation
http://numbers.computation.free.fr/Constants/constants.html
high p1 p0 low
+--------+--------+--------+--------+
| x1*y1 | x0*y0 |
+--------+--------+--------+--------+
+-+--------+--------+
|1| (x0*y1 + x1*y1) |
+-+--------+--------+
^carry from adding (x0*y1+x1*y1) together
+-+
|1|< carry from adding LOHALF t
+-+ to high half of p0
*/
DIGIT_T x0, y0, x1, y1;
DIGIT_T t, u, carry;
/* Split each x,y into two halves
x = x0 + B*x1
y = y0 + B*y1
where B = 2^16, half the digit size
Product is
xy = x0y0 + B(x0y1 + x1y0) + B^2(x1y1)
*/
x0 = LOHALF(x);
x1 = HIHALF(x);
y0 = LOHALF(y);
y1 = HIHALF(y);
/* Calc low part - no carry */
p[0] = x0 * y0;
/* Calc middle part */
t = x0 * y1;
u = x1 * y0;
t += u;
if (t < u)
carry = 1;
else
carry = 0;
/* This carry will go to high half of p[1]
+ high half of t into low half of p[1] */
carry = TOHIGH(carry) + HIHALF(t);
/* Add low half of t to high half of p[0] */
t = TOHIGH(t);
p[0] += t;
if (p[0] < t)
carry++;
p[1] = x1 * y1;
p[1] += carry;
return 0;
}
/* spDivide */
#define B (MAX_HALF_DIGIT + 1)
static void spMultSub(DIGIT_T uu[2], DIGIT_T qhat, DIGIT_T v1, DIGIT_T v0)
{
/* Compute uu = uu - q(v1v0)
where uu = u3u2u1u0, u3 = 0
and u_n, v_n are all half-digits
even though v1, v2 are passed as full digits.
*/
DIGIT_T p0, p1, t;
p0 = qhat * v0;
p1 = qhat * v1;
t = p0 + TOHIGH(LOHALF(p1));
uu[0] -= t;
if (uu[0] > MAX_DIGIT - t)
uu[1]--; /* Borrow */
uu[1] -= HIHALF(p1);
}
DIGIT_T spDivide(DIGIT_T *q, DIGIT_T *r, const DIGIT_T u[2], DIGIT_T v)
{ /* Computes quotient q = u / v, remainder r = u mod v
where u is a double digit
and q, v, r are single precision digits.
Returns high digit of quotient (max value is 1)
CAUTION: Assumes normalised such that v1 >= b/2
where b is size of HALF_DIGIT
i.e. the most significant bit of v should be one
In terms of half-digits in Knuth notation:
(q2q1q0) = (u4u3u2u1u0) / (v1v0)
(r1r0) = (u4u3u2u1u0) mod (v1v0)
for m = 2, n = 2 where u4 = 0
q2 is either 0 or 1.
We set q = (q1q0) and return q2 as "overflow"
*/
DIGIT_T qhat, rhat, t, v0, v1, u0, u1, u2, u3;
DIGIT_T uu[2], q2;
/* Check for normalisation */
if (!(v & HIBITMASK))
{ /* Stop if assert is working, else return error */
assert(v & HIBITMASK);
*q = *r = 0;
return MAX_DIGIT;
}
/* Split up into half-digits */
v0 = LOHALF(v);
v1 = HIHALF(v);
u0 = LOHALF(u[0]);
u1 = HIHALF(u[0]);
u2 = LOHALF(u[1]);
u3 = HIHALF(u[1]);
/* Do three rounds of Knuth Algorithm D Vol 2 p272 */
/* ROUND 1. Set j = 2 and calculate q2 */
/* Estimate qhat = (u4u3)/v1 = 0 or 1
then set (u4u3u2) -= qhat(v1v0)
where u4 = 0.
*/
/* [Replaced in Version 2] -->
qhat = u3 / v1;
if (qhat > 0)
{
rhat = u3 - qhat * v1;
t = TOHIGH(rhat) | u2;
if (qhat * v0 > t)
qhat--;
}
<-- */
qhat = (u3 < v1 ? 0 : 1);
if (qhat > 0)
{ /* qhat is one, so no need to mult */
rhat = u3 - v1;
/* t = r.b + u2 */
t = TOHIGH(rhat) | u2;
if (v0 > t)
qhat--;
}
uu[1] = 0; /* (u4) */
uu[0] = u[1]; /* (u3u2) */
if (qhat > 0)
{
/* (u4u3u2) -= qhat(v1v0) where u4 = 0 */
spMultSub(uu, qhat, v1, v0);
if (HIHALF(uu[1]) != 0)
{ /* Add back */
qhat--;
uu[0] += v;
uu[1] = 0;
}
}
q2 = qhat;
/* ROUND 2. Set j = 1 and calculate q1 */
/* Estimate qhat = (u3u2) / v1
then set (u3u2u1) -= qhat(v1v0)
*/
t = uu[0];
qhat = t / v1;
rhat = t - qhat * v1;
/* Test on v0 */
t = TOHIGH(rhat) | u1;
if ((qhat == B) || (qhat * v0 > t))
{
qhat--;
rhat += v1;
t = TOHIGH(rhat) | u1;
if ((rhat < B) && (qhat * v0 > t))
qhat--;
}
/* Multiply and subtract
(u3u2u1)' = (u3u2u1) - qhat(v1v0)
*/
uu[1] = HIHALF(uu[0]); /* (0u3) */
uu[0] = TOHIGH(LOHALF(uu[0])) | u1; /* (u2u1) */
spMultSub(uu, qhat, v1, v0);
if (HIHALF(uu[1]) != 0)
{ /* Add back */
qhat--;
uu[0] += v;
uu[1] = 0;
}
/* q1 = qhat */
*q = TOHIGH(qhat);
/* ROUND 3. Set j = 0 and calculate q0 */
/* Estimate qhat = (u2u1) / v1
then set (u2u1u0) -= qhat(v1v0)
*/
t = uu[0];
qhat = t / v1;
rhat = t - qhat * v1;
/* Test on v0 */
t = TOHIGH(rhat) | u0;
if ((qhat == B) || (qhat * v0 > t))
{
qhat--;
rhat += v1;
t = TOHIGH(rhat) | u0;
if ((rhat < B) && (qhat * v0 > t))
qhat--;
}
/* Multiply and subtract
(u2u1u0)" = (u2u1u0)' - qhat(v1v0)
*/
uu[1] = HIHALF(uu[0]); /* (0u2) */
uu[0] = TOHIGH(LOHALF(uu[0])) | u0; /* (u1u0) */
spMultSub(uu, qhat, v1, v0);
if (HIHALF(uu[1]) != 0)
{ /* Add back */
qhat--;
uu[0] += v;
uu[1] = 0;
}
/* q0 = qhat */
*q |= LOHALF(qhat);
/* Remainder is in (u1u0) i.e. uu[0] */
*r = uu[0];
return q2;
}
#endif /* Conditional single-digit mult & div routines */
/************************/
/* ARITHMETIC FUNCTIONS */
/************************/
DIGIT_T mpAdd(DIGIT_T w[], const DIGIT_T u[], const DIGIT_T v[], size_t ndigits)
{
/* Calculates w = u + v
where w, u, v are multiprecision integers of ndigits each
Returns carry if overflow. Carry = 0 or 1.
Ref: Knuth Vol 2 Ch 4.3.1 p 266 Algorithm A.
*/
DIGIT_T k;
size_t j;
assert(w != v);
/* Step A1. Initialise */
k = 0;
for (j = 0; j < ndigits; j++)
{
/* Step A2. Add digits w_j = (u_j + v_j + k)
Set k = 1 if carry (overflow) occurs
*/
w[j] = u[j] + k;
if (w[j] < k)
k = 1;
else
k = 0;
w[j] += v[j];
if (w[j] < v[j])
k++;
} /* Step A3. Loop on j */
return k; /* w_n = k */
}
DIGIT_T mpSubtract(DIGIT_T w[], const DIGIT_T u[], const DIGIT_T v[], size_t ndigits)
{
/* Calculates w = u - v where u >= v
w, u, v are multiprecision integers of ndigits each
Returns 0 if OK, or 1 if v > u.
Ref: Knuth Vol 2 Ch 4.3.1 p 267 Algorithm S.
*/
DIGIT_T k;
size_t j;
assert(w != v);
/* Step S1. Initialise */
k = 0;
for (j = 0; j < ndigits; j++)
{
/* Step S2. Subtract digits w_j = (u_j - v_j - k)
Set k = 1 if borrow occurs.
*/
w[j] = u[j] - k;
if (w[j] > MAX_DIGIT - k)
k = 1;
else
k = 0;
w[j] -= v[j];
if (w[j] > MAX_DIGIT - v[j])
k++;
} /* Step S3. Loop on j */
return k; /* Should be zero if u >= v */
}
int mpMultiply(DIGIT_T w[], const DIGIT_T u[], const DIGIT_T v[], size_t ndigits)
{
/* Computes product w = u * v
where u, v are multiprecision integers of ndigits each
and w is a multiprecision integer of 2*ndigits
Ref: Knuth Vol 2 Ch 4.3.1 p 268 Algorithm M.
*/
DIGIT_T k, t[2];
size_t i, j, m, n;
assert(w != u && w != v);
m = n = ndigits;
/* Step M1. Initialise */
for (i = 0; i < 2 * m; i++)
w[i] = 0;
for (j = 0; j < n; j++)
{
/* Step M2. Zero multiplier? */
if (v[j] == 0)
{
w[j + m] = 0;
}
else
{
/* Step M3. Initialise i */
k = 0;
for (i = 0; i < m; i++)
{
/* Step M4. Multiply and add */
/* t = u_i * v_j + w_(i+j) + k */
spMultiply(t, u[i], v[j]);
t[0] += k;
if (t[0] < k)
t[1]++;
t[0] += w[i+j];
if (t[0] < w[i+j])
t[1]++;
w[i+j] = t[0];
k = t[1];
}
/* Step M5. Loop on i, set w_(j+m) = k */
w[j+m] = k;
}
} /* Step M6. Loop on j */
return 0;
}
/* mpDivide */
static DIGIT_T mpMultSub(DIGIT_T wn, DIGIT_T w[], const DIGIT_T v[],
DIGIT_T q, size_t n)
{ /* Compute w = w - qv
where w = (WnW[n-1]...W[0])
return modified Wn.
*/
DIGIT_T k, t[2];
size_t i;
if (q == 0) /* No change */
return wn;
k = 0;
for (i = 0; i < n; i++)
{
spMultiply(t, q, v[i]);
w[i] -= k;
if (w[i] > MAX_DIGIT - k)
k = 1;
else
k = 0;
w[i] -= t[0];
if (w[i] > MAX_DIGIT - t[0])
k++;
k += t[1];
}
/* Cope with Wn not stored in array w[0..n-1] */
wn -= k;
return wn;
}
static int QhatTooBig(DIGIT_T qhat, DIGIT_T rhat,
DIGIT_T vn2, DIGIT_T ujn2)
{ /* Returns true if Qhat is too big
i.e. if (Qhat * Vn-2) > (b.Rhat + Uj+n-2)
*/
DIGIT_T t[2];
spMultiply(t, qhat, vn2);
if (t[1] < rhat)
return 0;
else if (t[1] > rhat)
return 1;
else if (t[0] > ujn2)
return 1;
return 0;
}
int mpDivide(DIGIT_T q[], DIGIT_T r[], const DIGIT_T u[],
size_t udigits, DIGIT_T v[], size_t vdigits)
{ /* Computes quotient q = u / v and remainder r = u mod v
where q, r, u are multiple precision digits
all of udigits and the divisor v is vdigits.
Ref: Knuth Vol 2 Ch 4.3.1 p 272 Algorithm D.
Do without extra storage space, i.e. use r[] for
normalised u[], unnormalise v[] at end, and cope with
extra digit Uj+n added to u after normalisation.
WARNING: this trashes q and r first, so cannot do
u = u / v or v = u mod v.
It also changes v temporarily so cannot make it const.
*/
size_t shift;
int n, m, j;
DIGIT_T bitmask, overflow;
DIGIT_T qhat, rhat, t[2];
DIGIT_T *uu, *ww;
int qhatOK, cmp;
/* Clear q and r */
mpSetZero(q, udigits);
mpSetZero(r, udigits);
/* Work out exact sizes of u and v */
n = (int)mpSizeof(v, vdigits);
m = (int)mpSizeof(u, udigits);
m -= n;
/* Catch special cases */
if (n == 0)
return -1; /* Error: divide by zero */
if (n == 1)
{ /* Use short division instead */
r[0] = mpShortDiv(q, u, v[0], udigits);
return 0;
}
if (m < 0)
{ /* v > u, so just set q = 0 and r = u */
mpSetEqual(r, u, udigits);
return 0;
}
if (m == 0)
{ /* u and v are the same length */
cmp = mpCompare(u, v, (size_t)n);
if (cmp < 0)
{ /* v > u, as above */
mpSetEqual(r, u, udigits);
return 0;
}
else if (cmp == 0)
{ /* v == u, so set q = 1 and r = 0 */
mpSetDigit(q, 1, udigits);
return 0;
}
}
/* In Knuth notation, we have:
Given
u = (Um+n-1 ... U1U0)
v = (Vn-1 ... V1V0)
Compute
q = u/v = (QmQm-1 ... Q0)
r = u mod v = (Rn-1 ... R1R0)
*/
/* Step D1. Normalise */
/* Requires high bit of Vn-1
to be set, so find most signif. bit then shift left,
i.e. d = 2^shift, u' = u * d, v' = v * d.
*/
bitmask = HIBITMASK;
for (shift = 0; shift < BITS_PER_DIGIT; shift++)
{
if (v[n-1] & bitmask)
break;
bitmask >>= 1;
}
/* Normalise v in situ - NB only shift non-zero digits */
overflow = mpShiftLeft(v, v, shift, n);
/* Copy normalised dividend u*d into r */
overflow = mpShiftLeft(r, u, shift, n + m);
uu = r; /* Use ptr to keep notation constant */
t[0] = overflow; /* Extra digit Um+n */
/* Step D2. Initialise j. Set j = m */
for (j = m; j >= 0; j--)
{
/* Step D3. Set Qhat = [(b.Uj+n + Uj+n-1)/Vn-1]
and Rhat = remainder */
qhatOK = 0;
t[1] = t[0]; /* This is Uj+n */
t[0] = uu[j+n-1];
overflow = spDivide(&qhat, &rhat, t, v[n-1]);
/* Test Qhat */
if (overflow)
{ /* Qhat == b so set Qhat = b - 1 */
qhat = MAX_DIGIT;
rhat = uu[j+n-1];
rhat += v[n-1];
if (rhat < v[n-1]) /* Rhat >= b, so no re-test */
qhatOK = 1;
}
/* [VERSION 2: Added extra test "qhat && "] */
if (qhat && !qhatOK && QhatTooBig(qhat, rhat, v[n-2], uu[j+n-2]))
{ /* If Qhat.Vn-2 > b.Rhat + Uj+n-2
decrease Qhat by one, increase Rhat by Vn-1
*/
qhat--;
rhat += v[n-1];
/* Repeat this test if Rhat < b */
if (!(rhat < v[n-1]))
if (QhatTooBig(qhat, rhat, v[n-2], uu[j+n-2]))
qhat--;
}
/* Step D4. Multiply and subtract */
ww = &uu[j];
overflow = mpMultSub(t[1], ww, v, qhat, (size_t)n);
/* Step D5. Test remainder. Set Qj = Qhat */
q[j] = qhat;
if (overflow)
{ /* Step D6. Add back if D4 was negative */
q[j]--;
overflow = mpAdd(ww, ww, v, (size_t)n);
}
t[0] = uu[j+n-1]; /* Uj+n on next round */
} /* Step D7. Loop on j */
/* Clear high digits in uu */
for (j = n; j < m+n; j++)
uu[j] = 0;
/* Step D8. Unnormalise. */
mpShiftRight(r, r, shift, n);
mpShiftRight(v, v, shift, n);
return 0;
}
int mpSquare(DIGIT_T w[], const DIGIT_T x[], size_t ndigits)
/* New in Version 2.0 */
{
/* Computes square w = x * x
where x is a multiprecision integer of ndigits
and w is a multiprecision integer of 2*ndigits
Ref: Menezes p596 Algorithm 14.16 with errata.
*/
DIGIT_T k, p[2], u[2], cbit, carry;
size_t i, j, t, i2, cpos;
assert(w != x);
t = ndigits;
/* 1. For i from 0 to (2t-1) do: w_i = 0 */
i2 = t << 1;
for (i = 0; i < i2; i++)
w[i] = 0;
carry = 0;
cpos = i2-1;
/* 2. For i from 0 to (t-1) do: */
for (i = 0; i < t; i++)
{
/* 2.1 (uv) = w_2i + x_i * x_i, w_2i = v, c = u
Careful, w_2i may be double-prec
*/
i2 = i << 1; /* 2*i */
spMultiply(p, x[i], x[i]);
p[0] += w[i2];
if (p[0] < w[i2])
p[1]++;
k = 0; /* p[1] < b, so no overflow here */
if (i2 == cpos && carry)
{
p[1] += carry;
if (p[1] < carry)
k++;
carry = 0;
}
w[i2] = p[0];
u[0] = p[1];
u[1] = k;
/* 2.2 for j from (i+1) to (t-1) do:
(uv) = w_{i+j} + 2x_j * x_i + c,
w_{i+j} = v, c = u,
u is double-prec
w_{i+j} is dbl if [i+j] == cpos
*/
k = 0;
for (j = i+1; j < t; j++)
{
/* p = x_j * x_i */
spMultiply(p, x[j], x[i]);
/* p = 2p <=> p <<= 1 */
cbit = (p[0] & HIBITMASK) != 0;
k = (p[1] & HIBITMASK) != 0;
p[0] <<= 1;
p[1] <<= 1;
p[1] |= cbit;
/* p = p + c */
p[0] += u[0];
if (p[0] < u[0])
{
p[1]++;
if (p[1] == 0)
k++;
}
p[1] += u[1];
if (p[1] < u[1])
k++;
/* p = p + w_{i+j} */
p[0] += w[i+j];
if (p[0] < w[i+j])
{
p[1]++;
if (p[1] == 0)
k++;
}
if ((i+j) == cpos && carry)
{ /* catch overflow from last round */
p[1] += carry;
if (p[1] < carry)
k++;
carry = 0;
}
/* w_{i+j} = v, c = u */
w[i+j] = p[0];
u[0] = p[1];
u[1] = k;
}
/* 2.3 w_{i+t} = u */
w[i+t] = u[0];
/* remember overflow in w_{i+t} */
carry = u[1];
cpos = i+t;
}
/* (NB original step 3 deleted in Menezes errata) */
/* Return w */
return 0;
}
int mpEqual(const DIGIT_T a[], const DIGIT_T b[], size_t ndigits)
{
/* Returns true if a == b, else false
*/
if (ndigits == 0) return -1;
while (ndigits--)
{
if (a[ndigits] != b[ndigits])
return 0; /* False */
}
return (!0); /* True */
}
int mpCompare(const DIGIT_T a[], const DIGIT_T b[], size_t ndigits)
{
/* Returns sign of (a - b)
*/
if (ndigits == 0) return 0;
while (ndigits--)
{
if (a[ndigits] > b[ndigits])
return 1; /* GT */
if (a[ndigits] < b[ndigits])
return -1; /* LT */
}
return 0; /* EQ */
}
int mpIsZero(const DIGIT_T a[], size_t ndigits)
{
/* Returns true if a == 0, else false
*/
size_t i;
if (ndigits == 0) return -1;
for (i = 0; i < ndigits; i++) /* Start at lsb */
{
if (a[i] != 0)
return 0; /* False */
}
return (!0); /* True */
}
size_t mpSizeof(const DIGIT_T a[], size_t ndigits)
{ /* Returns size of significant digits in a */
while(ndigits--)
{
if (a[ndigits] != 0)
return (++ndigits);
}
return 0;
}
size_t mpBitLength(const DIGIT_T d[], size_t ndigits)
/* Returns no of significant bits in d */
{
size_t n, i, bits;
DIGIT_T mask;
if (!d || ndigits == 0)
return 0;
n = mpSizeof(d, ndigits);
if (0 == n) return 0;