forked from bonzini/smalltalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LargeInt.st
1635 lines (1371 loc) · 43.3 KB
/
LargeInt.st
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
"======================================================================
|
| LargeInteger hierarchy Method Definitions
|
|
======================================================================"
"======================================================================
|
| Copyright 1999, 2000, 2001, 2002, 2008, 2009 Free Software Foundation, Inc.
| Written by Paolo Bonzini.
|
| This file is part of the GNU Smalltalk class library.
|
| The GNU Smalltalk class library is free software; you can redistribute it
| and/or modify it under the terms of the GNU Lesser General Public License
| as published by the Free Software Foundation; either version 2.1, or (at
| your option) any later version.
|
| The GNU Smalltalk class library is distributed in the hope that it will be
| useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
| General Public License for more details.
|
| You should have received a copy of the GNU Lesser General Public License
| along with the GNU Smalltalk class library; see the file COPYING.LIB.
| If not, write to the Free Software Foundation, 59 Temple Place - Suite
| 330, Boston, MA 02110-1301, USA.
|
======================================================================"
Integer subclass: LargeInteger [
<shape: #byte>
<category: 'Language-Data types'>
<comment: '
I represent a large integer, which has to be stored as a long sequence
of bytes. I have methods to do arithmetics and comparisons, but I need
some help from my children, LargePositiveInteger and LargeNegativeInteger,
to speed them up a bit.'>
Zero := nil.
One := nil.
ZeroBytes := nil.
OneBytes := nil.
LeadingZeros := nil.
TrailingZeros := nil.
LargeInteger class >> new [
<category: 'private'>
self shouldNotImplement
]
LargeInteger class >> initialize [
"Private - Initialize the receiver's class variables"
<category: 'private'>
ZeroBytes := #[0].
OneBytes := #[1].
Zero := LargeZeroInteger basicNew: 1.
One := (LargePositiveInteger basicNew: 1) setBytes: OneBytes.
"The leading zeros table is used in division and to compute
#highBit. It is obtained by:
LeadingZeros := ByteArray new: 255.
127 to: 1 by: -1 do: [ :i |
LeadingZeros at: i put: 1 + (LeadingZeros at: i + i).
]."
LeadingZeros := #[7 6 6 5 5 5 5 4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0].
"The trailing zeros table is used in the GCD algorithm. It is obtained by:
TrailingZeros := ByteArray new: 255.
2 to: 254 by: 2 do: [ :i |
TrailingZeros at: i put: 1 + (TrailingZeros at: i // 2).
]."
TrailingZeros := #[0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 5 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 6 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 5 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 7 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 5 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 6 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 5 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0 4 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0]
]
LargeInteger class >> test: selector with: a with: b [
<category: 'private'>
| result |
result := a perform: selector with: b.
a printNl.
b printNl.
result printNl
]
LargeInteger class >> from: byteArray [
"Private - Answer an instance of a descendant of LargeInteger representing the
number whose base-256 representation is in byteArray (least significant
byte first).
The answered LargeInteger has the smallest possible representation
(i.e. there are no spurious leading bytes set to all zeros or all ones)
and already belongs to the correct class, either LargePositiveInteger,
LargeNegativeInteger or LargeZeroInteger"
<category: 'private'>
| class lastSignificant byte |
lastSignificant := byteArray size.
[byte := byteArray at: lastSignificant.
lastSignificant = 1
ifTrue:
[byte = 0 ifTrue: [^Zero].
false "Leave the while loop"]
ifFalse:
["Check if the current byte is spurious AND has the same
sign as the previous"
(byte = 0 or: [byte = 255])
and: [(byte bitXor: (byteArray at: lastSignificant - 1)) < 128]]]
whileTrue: [lastSignificant := lastSignificant - 1].
class := (byteArray at: lastSignificant) < 128
ifTrue: [LargePositiveInteger]
ifFalse: [LargeNegativeInteger].
^(class basicNew: lastSignificant) setBytes: byteArray
]
LargeInteger class >> fromInteger: anInteger [
"Private - Answer an instance of a descendant of LargeInteger representing
the (small) Integer contained in anInteger.
The answered LargeInteger has the smallest possible representation
(i.e. there are no spurious leading bytes set to all zeros or all ones)
and already belongs to the correct class, either LargePositiveInteger,
LargeNegativeInteger or LargeZeroInteger"
<category: 'private'>
| bytes int |
anInteger isInteger ifFalse: [^anInteger].
bytes := ByteArray new: CLongSize.
int := anInteger.
1 to: CLongSize
do:
[:i |
bytes at: i put: (int bitAnd: 255).
int := int bitShift: -8].
^self from: bytes
]
LargeInteger class >> resultFrom: byteArray [
"Private - Answer an instance of a descendant of Integer representing the
number whose base-256 representation is in byteArray (least significant
byte first).
If a kind of LargeInteger is answered, it has the smallest possible
representation (i.e. there are no spurious leading bytes set to all zeros
or all ones); however it is possible that this method answers an Integer."
<category: 'private'>
| result accum size |
result := self from: byteArray.
size := result size.
size > CLongSize ifTrue: [^result].
size = CLongSize
ifTrue: [((result at: size) between: 64 and: 191) ifTrue: [^result]].
accum := result negative ifTrue: [-1] ifFalse: [0].
result size to: 1
by: -1
do: [:i | accum := (accum bitShift: 8) bitOr: (result at: i)].
^accum
]
hash [
"Answer an hash value for the receiver"
<category: 'built-ins'>
<primitive: VMpr_String_hash>
^0
]
size [
"Answer the number of indexed instance variable in the receiver"
<category: 'built-ins'>
<primitive: VMpr_Object_basicSize>
]
digitLength [
"Answer the number of base-256 digits in the receiver"
<category: 'built-ins'>
<primitive: VMpr_Object_basicSize>
]
at: anIndex [
"Answer the anIndex-th byte in the receiver's representation"
<category: 'built-ins'>
<primitive: VMpr_Object_basicAt>
^self mostSignificantByte
]
at: anIndex put: aNumber [
"Set the anIndex-th byte in the receiver's representation"
<category: 'built-ins'>
<primitive: VMpr_Object_basicAtPut>
self checkIndexableBounds: anIndex put: aNumber
]
primReplaceFrom: start to: stop with: replacementString startingAt: replaceStart [
"Private - Replace the characters from start to stop with new
characters contained in replacementString (which, actually, can be
any variable byte class), starting at the replaceStart location of
replacementString"
<category: 'built-ins'>
<primitive: VMpr_ArrayedCollection_replaceFromToWithStartingAt>
^self primitiveFailed
]
digitAt: anIndex [
"Answer the index-th base-256 digit of the receiver (byte), expressed
in two's complement"
<category: 'built-ins'>
<primitive: VMpr_Object_basicAt>
^self mostSignificantByte
]
digitAt: anIndex put: aNumber [
"Set the anIndex-th base-256 digit in the receiver's representation"
<category: 'built-ins'>
<primitive: VMpr_Object_basicAtPut>
self checkIndexableBounds: anIndex put: aNumber
]
asCNumber [
"Convert the receiver to a kind of number that is understood by
the C call-out mechanism."
<category: 'coercion'>
^self
]
asObject [
"This method always fails. The number of OOPs is far less than
the minimum number represented with a LargeInteger."
<category: 'disabled'>
self primitiveFailed
]
asObjectNoFail [
<category: 'disabled'>
^nil
]
= aNumber [
"Answer whether the receiver and aNumber identify the same number."
<category: 'testing'>
<primitive: VMpr_LargeInteger_eq>
(aNumber isKindOf: Number) ifFalse: [^false].
aNumber generality = self generality
ifFalse: [^self retryEqualityCoercing: aNumber].
self sign = aNumber sign ifFalse: [^false].
self size = aNumber size ifFalse: [^false].
self size to: 1
by: -1
do: [:index | (self at: index) = (aNumber at: index) ifFalse: [^false]].
^true
]
~= aNumber [
"Answer whether the receiver and aNumber identify different numbers."
<category: 'testing'>
<primitive: VMpr_LargeInteger_ne>
(aNumber isKindOf: Number) ifFalse: [^true].
aNumber generality = self generality
ifFalse: [^self retryInequalityCoercing: aNumber].
self sign = aNumber sign ifFalse: [^true].
self size = aNumber size ifFalse: [^true].
self size to: 1
by: -1
do: [:index | (self at: index) = (aNumber at: index) ifFalse: [^true]].
^false
]
< aNumber [
"Answer whether the receiver is smaller than aNumber"
<category: 'testing'>
<primitive: VMpr_LargeInteger_lt>
aNumber generality = self generality
ifFalse: [^self retryRelationalOp: #< coercing: aNumber].
self sign < aNumber sign ifTrue: [^true].
self sign > aNumber sign ifTrue: [^false].
self size > aNumber size ifTrue: [^self sign = -1].
aNumber size to: 1
by: -1
do:
[:index |
(self at: index) < (aNumber at: index) ifTrue: [^true].
(self at: index) > (aNumber at: index) ifTrue: [^false]].
^false
]
<= aNumber [
"Answer whether the receiver is smaller than aNumber or equal to it"
<category: 'testing'>
<primitive: VMpr_LargeInteger_le>
aNumber generality = self generality
ifFalse: [^self retryRelationalOp: #<= coercing: aNumber].
self sign < aNumber sign ifTrue: [^true].
self sign > aNumber sign ifTrue: [^false].
self size > aNumber size ifTrue: [^self sign = -1].
aNumber size to: 1
by: -1
do:
[:index |
(self at: index) < (aNumber at: index) ifTrue: [^true].
(self at: index) > (aNumber at: index) ifTrue: [^false]].
^true
]
> aNumber [
"Answer whether the receiver is greater than aNumber"
<category: 'testing'>
<primitive: VMpr_LargeInteger_gt>
aNumber generality = self generality
ifFalse: [^self retryRelationalOp: #> coercing: aNumber].
aNumber sign < self sign ifTrue: [^true].
aNumber sign > self sign ifTrue: [^false].
aNumber size > self size ifTrue: [^self sign = -1].
self size to: 1
by: -1
do:
[:index |
(aNumber at: index) < (self at: index) ifTrue: [^true].
(aNumber at: index) > (self at: index) ifTrue: [^false]].
^false
]
>= aNumber [
"Answer whether the receiver is greater than aNumber or equal to it"
<category: 'testing'>
<primitive: VMpr_LargeInteger_ge>
aNumber generality = self generality
ifFalse: [^self retryRelationalOp: #>= coercing: aNumber].
aNumber sign < self sign ifTrue: [^true].
aNumber sign > self sign ifTrue: [^false].
aNumber size > self size ifTrue: [^self sign = -1].
self size to: 1
by: -1
do:
[:index |
(aNumber at: index) < (self at: index) ifTrue: [^true].
(aNumber at: index) > (self at: index) ifTrue: [^false]].
^true
]
+ aNumber [
"Sum the receiver and aNumber, answer the result"
<category: 'arithmetic'>
self subclassResponsibility
]
- aNumber [
"Subtract aNumber from the receiver, answer the result"
<category: 'arithmetic'>
self subclassResponsibility
]
* aNumber [
"Multiply aNumber and the receiver, answer the result"
<category: 'arithmetic'>
| result |
<primitive: VMpr_LargeInteger_times>
aNumber sign = 0 ifTrue: [^0].
aNumber generality = self generality
ifFalse: [^self retryMultiplicationCoercing: aNumber].
result := self abs multiply: aNumber abs.
^self sign = aNumber sign ifTrue: [result] ifFalse: [result negated]
]
/ aNumber [
"Divide aNumber and the receiver, answer the result (an Integer or
Fraction)"
<category: 'arithmetic'>
| gcd |
aNumber sign = 0 ifTrue: [^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retryDivisionCoercing: aNumber].
gcd := self gcd: aNumber.
gcd = self
ifTrue: [^Fraction numerator: 1 denominator: (aNumber divExact: gcd)].
gcd = aNumber ifTrue: [^self divExact: gcd].
^Fraction numerator: (self divExact: gcd)
denominator: (aNumber divExact: gcd)
]
// aNumber [
"Divide aNumber and the receiver, answer the result truncated towards
-infinity"
<category: 'arithmetic'>
<primitive: VMpr_LargeInteger_intDiv>
aNumber sign = 0 ifTrue: [^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retry: #// coercing: aNumber].
self sign = aNumber sign
ifFalse: [^self - aNumber + aNumber sign quo: aNumber].
^self abs divide: aNumber abs
using: [:quo :rem :remNotZero | self species resultFrom: quo]
]
rem: aNumber [
"Divide aNumber and the receiver, answer the remainder truncated
towards 0"
<category: 'arithmetic'>
| result |
<primitive: VMpr_LargeInteger_rem>
aNumber sign = 0 ifTrue: [^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retry: #rem: coercing: aNumber].
^self abs divide: aNumber abs
using: [:quo :rem :remNotZero | self species resultFrom: rem]
]
quo: aNumber [
"Divide aNumber and the receiver, answer the result truncated
towards 0"
<category: 'arithmetic'>
| result |
<primitive: VMpr_LargeInteger_quo>
aNumber sign = 0 ifTrue: [^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retry: #quo: coercing: aNumber].
result := self abs divide: aNumber abs
using: [:quo :rem :remNotZero | self species resultFrom: quo].
^self sign = aNumber sign ifTrue: [result] ifFalse: [result negated]
]
divExact: aNumber [
"Dividing receiver by arg assuming that the remainder is zero, and answer
the result"
<category: 'arithmetic'>
| result |
<primitive: VMpr_LargeInteger_divExact>
aNumber sign = 0
ifTrue:
["Same as quo:, not worthwhile to implement it in Smalltalk."
^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retry: #divExact: coercing: aNumber].
result := self abs divide: aNumber abs
using: [:quo :rem :remNotZero | self species resultFrom: quo].
^self sign = aNumber sign ifTrue: [result] ifFalse: [result negated]
]
\\ aNumber [
"Divide aNumber and the receiver, answer the remainder truncated
towards -infinity"
<category: 'arithmetic'>
<primitive: VMpr_LargeInteger_modulo>
aNumber sign = 0 ifTrue: [^self zeroDivide].
self sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retry: #\\ coercing: aNumber].
aNumber sign < 0 ifTrue: [^(self negated \\ aNumber negated) negated].
^self abs divide: aNumber
using:
[:quo :rem :remNotZero |
"must be positive"
| remInteger |
remInteger := self species resultFrom: rem.
(remNotZero and: [self negative])
ifTrue: [aNumber - remInteger]
ifFalse: [remInteger]]
]
estimatedLog [
"Answer an estimate of (self abs floorLog: 10)"
<category: 'arithmetic'>
^(self size asFloatD * 8.0 / FloatD log10Base2) ceiling
]
negated [
"Answer the receiver's negated"
<category: 'arithmetic'>
| newBytes carry a |
<primitive: VMpr_LargeInteger_negated>
newBytes := ByteArray new: self size + 1.
carry := 256.
1 to: self size
do:
[:index |
a := carry - (self at: index).
a < 256
ifTrue: [carry := 255]
ifFalse:
[carry := 256.
a := a - 256].
newBytes at: index put: a].
newBytes at: newBytes size put: (self mostSignificantByte bitXor: 255).
^self species resultFrom: newBytes
]
lowBit [
"Return the index of the lowest order 1 bit of the receiver."
<category: 'bit operations'>
| each |
1 to: self size
do:
[:index |
(each := self digitAt: index) = 0
ifFalse: [^index * 8 - 7 + (TrailingZeros at: each)]].
^self highBit
]
bitAnd: aNumber [
"Answer the receiver ANDed with aNumber"
<category: 'bit operations'>
| newBytes |
<primitive: VMpr_LargeInteger_bitAnd>
aNumber isInteger
ifFalse: [^SystemExceptions.WrongClass signalOn: aNumber mustBe: Integer].
aNumber generality = self generality
ifFalse: [^self retry: #bitAnd: coercing: aNumber].
newBytes := ByteArray new: (self size max: aNumber size).
1 to: newBytes size
do: [:index | newBytes at: index put: ((self at: index) bitAnd: (aNumber at: index))].
^self species resultFrom: newBytes
]
bitAt: aNumber [
"Answer the aNumber-th bit in the receiver, where the LSB is 1"
<category: 'bit operations'>
| bit |
bit := aNumber - 1.
^(self at: bit // 8 + 1) bitAt: bit \\ 8 + 1
]
bitInvert [
"Answer the receiver's 1's complement"
<category: 'bit operations'>
| bytes |
<primitive: VMpr_LargeInteger_bitInvert>
bytes := ByteArray new: self size + 1.
bytes at: bytes size put: (self mostSignificantByte bitXor: 255).
1 to: self size
do: [:index | bytes at: index put: ((self at: index) bitXor: 255)].
^self species resultFrom: bytes
]
bitOr: aNumber [
"Answer the receiver ORed with aNumber"
<category: 'bit operations'>
| newBytes |
<primitive: VMpr_LargeInteger_bitOr>
aNumber isInteger
ifFalse: [^SystemExceptions.WrongClass signalOn: aNumber mustBe: Integer].
aNumber generality = self generality
ifFalse: [^self retry: #bitOr: coercing: aNumber].
newBytes := ByteArray new: (self size max: aNumber size).
1 to: newBytes size
do: [:index | newBytes at: index put: ((self at: index) bitOr: (aNumber at: index))].
^self species resultFrom: newBytes
]
bitXor: aNumber [
"Answer the receiver XORed with aNumber"
<category: 'bit operations'>
| newBytes |
<primitive: VMpr_LargeInteger_bitXor>
aNumber isInteger
ifFalse: [^SystemExceptions.WrongClass signalOn: aNumber mustBe: Integer].
aNumber generality = self generality
ifFalse: [^self retry: #bitXor: coercing: aNumber].
newBytes := ByteArray new: (self size max: aNumber size).
1 to: newBytes size
do: [:index | newBytes at: index put: ((self at: index) bitXor: (aNumber at: index))].
^self species resultFrom: newBytes
]
bitShift: aNumber [
"Answer the receiver shifted by aNumber places"
<category: 'bit operations'>
<primitive: VMpr_LargeInteger_bitShift>
aNumber isInteger
ifFalse: [^SystemExceptions.WrongClass signalOn: aNumber mustBe: Integer].
^aNumber > 0
ifTrue: [self basicLeftShift: aNumber]
ifFalse: [self basicRightShift: aNumber negated]
]
raisedToInteger: n [
"Return self raised to the anInteger-th power"
"For LargeIntegers only, it pays off to strip the rightmost
0 bits and put them back later with a left shift..."
<category: 'accessing'>
| nbit |
nbit := 1.
[(self bitAt: nbit) = 0] whileTrue: [nbit := nbit + 1].
nbit = 1 ifTrue: [^super raisedToInteger: n].
nbit := nbit - 1.
^((self bitShift: nbit negated) raisedToInteger: n) bitShift: nbit * n
]
basicLeftShift: totalShift [
"Private - Left shift the receiver by aNumber places"
<category: 'primitive operations'>
| newBytes byteShift carry shift a |
byteShift := totalShift // 8.
shift := totalShift bitAnd: 7.
newBytes := ByteArray new: (totalShift + 7) // 8 + self size.
"That `+ 1' in the #to:do: performs an extra iteration that stores the
last carry in the extra byte reserved in the previous statement"
carry := 0.
1 to: newBytes size - byteShift
do:
[:index |
a := ((self at: index) bitShift: shift) + carry.
carry := a bitShift: -8.
a := a bitAnd: 255.
newBytes at: index + byteShift put: a].
^self species resultFrom: newBytes
]
basicRightShift: totalShift [
"Private - Right shift the receiver by 'shift' places"
<category: 'primitive operations'>
| shift newBytes byteShift carryShift x a |
byteShift := totalShift // 8.
shift := (totalShift bitAnd: 7) negated.
carryShift := 8 + shift.
self size <= (byteShift - 1) ifTrue: [^0].
newBytes := ByteArray new: self size - byteShift + 1.
x := (self at: byteShift + 1) bitShift: shift.
byteShift + 1 to: self size
do:
[:j |
a := self at: j + 1.
newBytes at: j - byteShift put: ((a bitShift: carryShift) bitAnd: 255) + x.
x := a bitShift: shift].
newBytes at: newBytes size put: self mostSignificantByte.
^self species resultFrom: newBytes
]
largeNegated [
"Private - Same as negated, but always answer a LargeInteger"
<category: 'primitive operations'>
| newBytes carry a |
newBytes := ByteArray new: self size + 1.
carry := 256.
1 to: self size
do:
[:index |
a := carry - (self at: index).
a < 256
ifTrue: [carry := 255]
ifFalse:
[carry := 256.
a := a - 256].
newBytes at: index put: a].
newBytes at: newBytes size put: (self mostSignificantByte bitXor: 255).
^self species from: newBytes
]
zero [
"Coerce 0 to the receiver's class"
<category: 'coercion'>
^Zero
]
unity [
"Coerce 1 to the receiver's class"
<category: 'coercion'>
^One
]
coerce: aNumber [
"Truncate the number; if needed, convert it to LargeInteger
representation."
<category: 'coercion'>
aNumber = 0 ifTrue: [^Zero].
^aNumber isInteger
ifTrue: [self species fromInteger: aNumber]
ifFalse: [self species fromInteger: aNumber truncated]
]
generality [
"Answer the receiver's generality"
<category: 'coercion'>
^200
]
mostSignificantByte [
"Private - Answer the value of the most significant byte"
<category: 'private'>
self subclassResponsibility
]
species [
<category: 'private'>
^LargeInteger
]
bytes [
<category: 'private'>
| bytes |
bytes := ByteArray new: self size + 1.
bytes
replaceFrom: 1
to: self size
with: self
startingAt: 1.
bytes at: bytes size put: self mostSignificantByte.
^bytes
]
setBytes: aByteArray [
<category: 'private'>
self
primReplaceFrom: 1
to: self size
with: aByteArray
startingAt: 1
]
]
LargeInteger subclass: LargeNegativeInteger [
<shape: #byte>
<category: 'Language-Data types'>
<comment: '
Just like my brother LargePositiveInteger, I provide a few methods that
allow LargeInteger to determine the sign of a large integer in a fast way
during its calculations. For example, I know that I am smaller than any
LargePositiveInteger'>
+ aNumber [
"Sum the receiver and aNumber, answer the result"
"All we have to do is convert the two numbers to two positive
numbers and make LargePositiveInteger do the calculation.
Use #largeNegated to save some coercions."
<category: 'reverting to LargePositiveInteger'>
<primitive: VMpr_LargeInteger_plus>
aNumber sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retrySumCoercing: aNumber].
^aNumber sign = -1
ifTrue: [(self largeNegated + aNumber largeNegated) negated]
ifFalse: [(self largeNegated - aNumber) negated]
]
- aNumber [
"Subtract aNumber from the receiver, answer the result"
"All we have to do is convert the two numbers to two positive
numbers and make LargePositiveInteger do the calculation.
Use #largeNegated to save some coercions."
<category: 'reverting to LargePositiveInteger'>
<primitive: VMpr_LargeInteger_minus>
aNumber sign = 0 ifTrue: [^self].
aNumber generality = self generality
ifFalse: [^self retryDifferenceCoercing: aNumber].
^aNumber sign = -1
ifTrue: [(self largeNegated - aNumber largeNegated) negated]
ifFalse: [(self largeNegated + aNumber) negated]
]
highBit [
"Answer the receiver's highest bit's index"
<category: 'reverting to LargePositiveInteger'>
^(self at: self size) = 255
ifTrue: [^8 * self size - 16 + ((self at: self size - 1) - 256) highBit]
ifFalse: [^8 * self size - 8 + ((self at: self size) - 256) highBit]
]
gcd: anInteger [
"Return the greatest common divisor between the receiver and anInteger"
<category: 'reverting to LargePositiveInteger'>
<primitive: VMpr_LargeInteger_gcd>
^self negated gcd: anInteger abs
]
positive [
"Answer whether the receiver is >= 0"
<category: 'numeric testing'>
^false
]
strictlyPositive [
"Answer whether the receiver is > 0"
<category: 'numeric testing'>
^false
]
negative [
"Answer whether the receiver is < 0"
<category: 'numeric testing'>
^true
]
abs [
"Answer the receiver's absolute value."
"This is surely a large integer (while `aLargePositiveInteger negated'
might be the smallest small integer)."
<category: 'numeric testing'>
<primitive: VMpr_LargeInteger_negated>
^self largeNegated
]
sign [
"Answer the receiver's sign"
<category: 'numeric testing'>
^-1
]
asFloatD [
"Answer the receiver converted to a FloatD"
<category: 'converting'>
^self negated asFloatD negated
]
asFloatE [
"Answer the receiver converted to a FloatE"
<category: 'converting'>
^self negated asFloatE negated
]
asFloatQ [
"Answer the receiver converted to a FloatQ"
<category: 'converting'>
^self negated asFloatQ negated
]
mostSignificantByte [
"Private - Answer the value of the most significant byte"
<category: 'private'>
^255
]
]
LargeInteger subclass: LargePositiveInteger [
<shape: #byte>
<category: 'Language-Data types'>
<comment: '
Just like my brother LargeNegativeInteger, I provide a few methods that
allow LargeInteger to determine the sign of a large integer in a fast way
during its calculations. For example, I know that I am larger than any
LargeNegativeInteger. In addition I implement the guts of arbitrary
precision arithmetic.'>
+ aNumber [
"Sum the receiver and aNumber, answer the result"
<category: 'arithmetic'>
| newBytes carry a b result |
<primitive: VMpr_LargeInteger_plus>
aNumber sign = 0 ifTrue: [^self].
aNumber sign = -1 ifTrue: [^self - aNumber negated].
aNumber generality = self generality
ifFalse: [^self retrySumCoercing: aNumber].
newBytes := ByteArray new: (self size max: aNumber size) + 1.
carry := 0.
1 to: newBytes size - 1
do:
[:index |
result := (self at: index) + (aNumber at: index) + carry.
result > 255
ifTrue:
[carry := 1.
result := result - 256]
ifFalse: [carry := 0].
newBytes at: index put: result].
newBytes at: newBytes size put: carry.
^LargeInteger resultFrom: newBytes
]
- aNumber [
"Subtract aNumber from the receiver, answer the result"
<category: 'arithmetic'>
| newBytes carry a b result |
<primitive: VMpr_LargeInteger_minus>
aNumber sign = 0 ifTrue: [^self].
aNumber sign = -1 ifTrue: [^self + aNumber negated].
aNumber generality = self generality
ifFalse: [^self retryDifferenceCoercing: aNumber].
newBytes := ByteArray new: (self size max: aNumber size) + 1.
carry := 0.
1 to: newBytes size - 1
do:
[:index |
result := (self at: index) - (aNumber at: index) + carry.
result < 0
ifTrue:
[carry := -1.
result := result + 256]
ifFalse: [carry := 0].
newBytes at: index put: result].
newBytes at: newBytes size put: (carry bitAnd: 255).
^LargeInteger resultFrom: newBytes
]
gcd: anInteger [
"Calculate the GCD between the receiver and anInteger"
"Binary GCD - See Knuth `Seminumerical algorithms', Vol 2, 4.5.2
It was adapted to remove the variable `r' and to only work with
unsigned numbers"
<category: 'arithmetic'>
| adjust t tmp u v |
<primitive: VMpr_LargeInteger_gcd>
(self sign bitAnd: anInteger sign) = 0 ifTrue: [^self + anInteger].
u := self bytes.
v := anInteger abs.
v generality = self generality ifFalse: [v := self coerce: v].
v := v bytes.
"Divide u and v by 2 as long as they are both even"
adjust := t := self bytesTrailingZeros: u.
self bytesRightShift: u big: t.
adjust := adjust min: (t := self bytesTrailingZeros: v).
self bytesRightShift: v big: t.
u size = v size
ifFalse:
[u size < v size
ifTrue: [u := u copyGrowTo: v size]
ifFalse: [v := v copyGrowTo: u size]].
"Well, this is it -- the stuff up to this point was just set up"
[t := self
bytes: u
from: 1
compare: v.
t = 0]
whileFalse:
[t < 0
ifTrue:
[t := v.
v := u.
u := t].