-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbignum.js
6910 lines (6532 loc) · 180 KB
/
bignum.js
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
"use strict";
/*
Errors found by an unbridled eslint are mostly intentionally (e.g.: "=="
instead of "===") but should be checked carefully nevertheless.
The command
eslint --rule "no-unused-vars:0, no-console:0, quotes:0, new-cap:0, no-empty:0, no-spaced-func:0, no-cond-assign:0, no-constant-condition:0, no-underscore-dangle:0, eqeqeq:0, camelcase:0, no-extend-native:0, yoda:0, eol-last:0, global-strict:0" bignum.js
will result in the following output (linenumbers may change)
250:21 error 'DataView' is not defined no-undef
303:19 error 'console' is not defined no-undef
304:12 error 'console' is not defined no-undef
306:19 error 'alert' is not defined no-undef
246:11 error MP_L1_SIZE was used before it was defined no-use-before-define
2330:17 error div2n1n was used before it was defined no-use-before-define
2361:13 error div3n2n was used before it was defined no-use-before-define
2366:13 error div3n2n was used before it was defined no-use-before-define
The reasons for occuring and/or the reasons for ignoring:
205:21 typed arrays are not in ECMAScript 5.1 but implemented everywhere
303:19 we check if something is defined, so it is possible it wasn't defined
304:12 in the first place
306:19 -"-
246:11 basically the same as above
2330:17 _"_
2361:13 _"_
2366:13 _"_
*/
/*
Formatted with
js-beautify -b "expand" -w 80 -s 4 -k --end_with_newline bignum.js
*/
/*
###### ####### # # # ###### ####### ###
# # # # # # # # # # # ###
# # # # # # # # # # # ###
###### ##### # # # # # ###### ##### #
# # # # # # ####### # # #
# # # # # # # # # # # ###
###### ####### ## ## # # # # ####### ###
This code is completely untested, might kill you cat, mother-in-law, landlord,
investment-banker (you once were in need of an investment-banker?) and worst of
all: it may not even compile!
*/
// Needs ECMAScript 5.1 compliant engine to work
// Please be aware that I didn't wrote "Needs ECMAScript >5.1 compliant engine
// to work" although it should be upwards comnpatible to "Harmony" at least
/*
This code contains some ports of Libtommath (public domain) and some ports of
older SunPro code (License below)
*/
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/*
The snippets with code from SunPro are annotated as such. Replace if
the above license is a problem.
It seems as if no SunPro code gets used up until this comment has been written.
*/
/*
TODO: Quite a lot.
- should be modern but also kept legible and easy to follow, e.g. putting the
whole thing in a module for easier use might be a nice idea.
- some things are superfluous
- in urgent need of correct error-checking with try/catch and error throw-ing
- some of the inner loops can make use of multiple cores/processors
but the thread-like Worker() is quite restricted, so it may or may not of
any use here
- Make use of a general namespace for all of the global variables
(Bignum or something which will make sense after adding of a Bigfloat )
- ECMA 5 offers typed arrays, check if Uint32Arrays do the job better
(needs a byteorder check); see also Float64Array for the FFT.
http://jsperf.com/array-vs-uint32array says it is faster but not much
http://jsperf.com/array-vs-uint32array/7 says it is slower
http://jsperf.com/float64array/2 much slower
Interresting benchmark:
http://jsperf.com/greatest-common-divisor-uint32array/3
The Browserscope inlined beneath shows Chrome 31.0.1600 with basically
all the same results. Could it be that Chrome optimizes every function
into the same "assembler" code? Could it be a good idea to check the
computated results? ;-)
- there are some tricks in ASM.js which needs to be done here
especially "x>>>0" to make it unsigned and "x|0" to make it an integer (x
may be an explicite number e.g.: "123>>>0" or "0|0" respectively)
but the whole thing is quite complicated to do by hand. I don't think
I'll do the whole asm.js thingie by hand, the memory managment is too
complicated. Says an old C-programmer ;-)
- some things are really stupid. Feel free to post them at thedailywtf.com,
the folks there will take care of the "make fun of it and ridicule" part but
do a CC to me to give me a chance to correct it if it is a real bug.
And only if it is a real bug, simple idiocy does not count ;-)
*/
// Flagnames taken from libtommath
/**
Preallocated length of bitarray. Probably unnecessary, may be removed in the
future. Or not if and when typed arrays gets used instead of normal ones.
The latter is unlikely until no function like realloc or similar allow for
dynamic growth of the buffer.
@memberof Bigint
@const {number}
@default
*/
var MP_PREC = 5;
/**
Flag for positive value
@const {number}
@default
*/
var MP_ZPOS = 1;
/**
Flag for negative value
@const {number}
@default
*/
var MP_NEG = -1;
/**
Largest integer possible with native number
@const {number}
@default
*/
var MP_LONG_MAX = 9007199254740992;
/**
Smallest integer possible with native number
@const {number}
@default
*/
var MP_LONG_MIN = -9007199254740992;
/**
Largest 32-bit integer (e.g.: for boolean operations)
@const {number}
@default
*/
var MP_INT_MAX = 0xffffffff;
/**
Smallest 32-bit integer (e.g.: for boolean operations)
@const {number}
@default
*/
var MP_INT_MIN = -0xffffffff;
/**
Comparing: value for less-than
@const {number}
@default
*/
var MP_LT = -1;
/**
Comparing: value for equal
@const {number}
@default
*/
var MP_EQ = 0;
/**
Comparing: value for greater-than
@const {number}
@default
*/
var MP_GT = 1;
/**
Common Errors: no error
@const {number}
@default
*/
var MP_OKAY = 0;
/**
Common Errors: Domain error (input wrong)
@const {number}
@default
*/
var MP_DOMAIN = -2;
/**
Common Errors: range error
@const {number}
@default
*/
var MP_VAL = -3;
/**
Common Errors: range error
@const {number}
@default
*/
var MP_RANGE = MP_VAL;
/**
Common Errors: Function not supported (you may come back later?)
@const {number}
@default
*/
var MP_NOTSUP = -4;
/**
Common Errors: Function not supported (you may come back later?)
@const {number}
@default
*/
var MP_NOSYS = MP_NOTSUP;
// Value too large for something to be specified elsewhere
/**
Common Errors: Overflow
@const {number}
@default
*/
var MP_OVERFLOW = -5;
/**
Common Errors: Underflow
@const {number}
@default
*/
var MP_UNDERFLOW = -6;
/**
Common Errors: total loss of significance
@const {number}
@default
*/
var MP_TLOSS = -7;
/**
Common Errors: partial loss of significance
@const {number}
@default
*/
var MP_PLOSS = -8;
/**
Common Errors: Pole error (singularity)
@const {number}
@default
*/
var MP_SING = -9;
// A bit of Bool
/**
An alias for true
@const {bool}
@default
*/
var MP_YES = true;
/**
An alias for false
@const {bool}
@default
*/
var MP_NO = false;
/**
Cut-Off values: Karatsuba multiplication
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var KARATSUBA_MUL_CUTOFF = 125;
/**
Cut-Off values: Karatsuba squaring
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var KARATSUBA_SQR_CUTOFF = 200;
/**
Cut-Off values: Toom-Cook 3-way multiplication
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var TOOM_COOK_MUL_CUTOFF = 475;
/**
Cut-Off values: Toom-Cook 3-way squaring
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var TOOM_COOK_SQR_CUTOFF = 600;
/**
Cut-Off values: FFT-multiplication
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var FFT_MUL_CUTOFF = 4096;
// do one karatsuba mul. if limit is reached
// 2^23 is below limit and still 8,388,608 limbs large which is > 10^(10^14)
/**
Cut-Off values: Upper limit of rounding errors for FFT. It will do one round
of Karatusba to reduce the individual sizes.
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var FFT_UPPER_LIMIT = 1 << 23; // only if NTT is not implemented
/**
Cut-Off values: FFT-squaring
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var FFT_SQR_CUTOFF = 2048;
/*
var NTT_MUL_CUTOFF;
var NTT_SQR_CUTOFF;
var TOOM_COOK_4_MUL_CO;
var TOOM_COOK_4_SQR_CO;
var TOOM_COOK_5_MUL_CO;
var TOOM_COOK_5_SQR_CO;
*/
// all limits are in limbs exept when indicated differently
// Burnikel-Ziegel division (divide&conquer taken literally)
/**
Cut-Off values: Burnikel-Ziegel division<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var BURN_ZIEG_NUMERATOR = 500;
/**
Cut-Off values: Burnikel-Ziegel division<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var BURN_ZIEG_DENOMINATOR = 300;
/**
Cut-Off values: Burnikel-Ziegel division, when to do the normal division
instead of recursing (value in bits)<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var BURN_ZIEG_CUTOFF = 3000;
// for N<=2*D size of numerator, size of denominator otherwise
// Reason: Barrett-division works only with multiplication faster than
// O(n^2) in theory, in praxi it needs the O(n^1.465) of Toom-Cook 3-way, 2-way
// does not seem fast enough
// TODO: find the bug
/**
@ignore
*/
var BARRETT_NUMERATOR = 3800000; // was 3800
/**
@ignore
*/
var BARRETT_DENOMINATOR = 1900000; // was 1900
// when to do some rounds of Newton-Raphson to refine mu (the reciprocal) for
// Barrett-division
/**
@ignore
*/
var BARRETT_NEWTON_CUTOFF = 100;
/**
Cut-Off values: Division by multiplication with reciprocal (simple Newton-Raphson)
These are the ranges where the steps of FFT multiplication can influence
some specific cutoffs values. Truncated FFT is planned but not yet implemented.<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var NEWTON_NUMERATOR = 8000;
/**
Cut-Off values: Division by multiplication with reciprocal (simple Newton-Raphson)
These are the ranges where the steps of FFT multiplication can influence
some specific cutoffs values. Truncated FFT is planned but not yet implemented.<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var NEWTON_DENOMINATOR = 4000;
/**
Cut-Off values: Division by multiplication with reciprocal (simple Newton-Raphson)
A reasonabel general cutoff if the k of N=k*D is not too large
These are the ranges where the steps of FFT multiplication can influence
some specific cutoffs values. Truncated FFT is planned but not yet implemented.<br>
(YMMV. Please send a note if it varies)
@memberof Bigint
@const {number}
@default
*/
var NEWTON_CUTOFF = 77000; // >2 mio bits
// Bits per digit. See below for details
/**
Bits per digit<br>
Some of the functions rely on this constant being set to 26, the default value,
so if you want to change it, look them up.
@const {number}
@default
*/
var MP_DIGIT_BIT = 26;
// Digit mask (e.g.: 0x3fffffff for 30 bit long digits)
/**
Digit mask
@const {number}
@default
*/
var MP_MASK = ((1 << MP_DIGIT_BIT) - 1);
// Too large a digit by one. (radix)
/**
Size of radix (limb)
@const {number}
@default
*/
var MP_DIGIT_MAX = (1 << MP_DIGIT_BIT);
// half digits needed for FFT multiplication
/**
Half digits needed for FFT multiplication<br>
Half of the number of digit bits
@memberof Bigint
@const {number}
@default
*/
var MP_HALF_DIGIT_BIT = (MP_DIGIT_BIT >> 1);
/**
Half digits needed for FFT multiplication<br>
Half of the size of the radix
@memberof Bigint
@const {number}
@default
*/
var MP_HALF_DIGIT = (1 << MP_HALF_DIGIT_BIT);
/**
Half digits needed for FFT multiplication<br>
Half of the size of the digit mask
@memberof Bigint
@const {number}
@default
*/
var MP_HALF_DIGIT_MASK = (MP_HALF_DIGIT - 1);
if (typeof MP_L1_SIZE === 'undefined') {
/**
Used in FFT code
The size of the L1-cache in bytes. The number here is that of the data cache
part of an AMD Duron. The Linux kernel gives a lot of information e.g.:
<pre>
grep . /sys/devices/system/cpu/cpu0/cache/index
</pre>
There is also lscpu(1) wich is easier to use.
On Windows:
{@link http://msdn.microsoft.com/en-us/library/ms683194.aspx}<br>
{@link http://www.cpuid.com/softwares/cpu-z.htm}<br>
Lack of access to a Mac leaves that part blank. The new MacOS is based on BSD,
so 'dmesg' might work or
<pre>
cat /var/run/dmesg.boot | grep CPU
</pre>
If in doubt leave the value as it is but give 32 kib (32768) at least a try.
@memberof Bigint
@const {number}
@default
*/
var MP_L1_SIZE = 65536;
}
/**
Memory for some of the bit-juggling below: an 8 (eight) byte buffer
@const {object}
@default
*/
var double_int = new DataView(new ArrayBuffer(8));
/**
Modular multiplicative inverse of 3 (three) for exactDiv3.<br>
Has no default value because of the different possible sizes of the limb
@memberof Bigint
@const {Bigint}
*/
var MOD_MUL_INV_THREE;
/**
Half of the modular multiplicative inverse of 3 (three) for exactDiv3.<br>
Has no default because of the different possible sizes of the limb
@memberof Bigint
@const {Bigint}
@default
*/
var MOD_MUL_INV_THREE_HALF;
/**
checking for endianess (little endian only for now)
The method (shamelessly stolen from emscripten) is a bit more complicated than
I want it but things like
<pre>
var byteorder;
var test = 0xaabbccdd;
if((test&0xff) == 0xdd) byteorder = "1234";
else if((test&0xff) == 0xaa) byteorder = "4321";
else if((test&0xff) == 0xbb){
print( "Please send a note to czurnieden@gmx.de and tell me"
+ " which browser/javascript parser you installed on"
+ " which machine (PDP-11, old VAX in comp.mode, emulator etc.) and"
+ " how... no, wait: WHY did you do that? (as if I do not know the"
+ "answer)");
byteorder = "3412";
}
// Yes, there exist bytorders that are even more exotic than
// the PDP-11 byteorder. Please send a note to the author.
else return undefined;
return byteorder
</pre>
are a bit dubious ("test" needs to act like an unsigned 32 bit integer. Does
it? Always?), so I've chosen the long and tedious but hopefully correct way.
<br>
Throws a FatalError which you may or may not want to catch.
<br>
It seems as if the endianess of typed arrays gets fixed in the next ECMAScript
standard to big-endian. But only them.
@throws {FatalError}
*/
var __bigint_check_endianess = (function() {
try {
var buffer = new ArrayBuffer(8);
var strerror =
'Bigint was written for a little-endian system only, sorry.';
var MP_ENDIANESS_TEST_32 = new Int32Array(buffer);
var MP_ENDIANESS_TEST_8 = new Uint8Array(buffer);
MP_ENDIANESS_TEST_32[0] = 0xff;
if (MP_ENDIANESS_TEST_8[3] === 0xff &&
MP_ENDIANESS_TEST_8[0] === 0) {
throw {
name: 'FatalError',
message: strerror
};
}
} catch (e) {
if (typeof console.log === 'function') {
console.log(e.message);
}
if (typeof alert === 'function') {
alert(e.message);
}
throw {
name: 'FatalError',
message: strerror
};
}
})();
/******************************************************************************
*
* Some helpers to make it stand-alone
*
******************************************************************************/
/**
Generalized, extendable "typeof" function. Please see the source for how to add
more objects.
@param {*} obj just anything
@return {string} lowercase'd name of input
*/
function xtypeof(obj) {
'use strict';
// try it the traditional way
var tmp = typeof obj;
if (tmp !== 'object') {
return tmp;
} else {
// try the toString prototype
tmp = Object.prototype.toString.call(obj);
// It is one of the build-ins
// Format is defined in the ECMAScript 5.1 in 5.2.4.2
// http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.4.2
if (tmp !== '[object Object]') {
return tmp.slice(8, -1).toLowerCase();
} else {
// Put your own objects here
// The key is the lowercase'd name of the object,
// the value is the correctly typed name of the object.
// The value must be a String, hence in quotes.
var list = {
bigint: 'Bigint',
//bigfloat: 'Bigfloat',
bigrational: 'Bigrational',
complex: 'Complex'
};
for (var p in list) {
try {
// Yes, kids, eval() is eeeeevil!
// Undefined entries will cause a ReferenceError.
tmp = eval(list[p]);
} catch (e) {
// Nothing to catch here because the evidence
// of non-existance is sufficient for our needs,
// so let's...
continue;
}
if (obj instanceof tmp) {
return p;
}
}
return 'object';
}
}
}
/**
A primesieve, full implementation.
@see {@link https://github.com/czurnieden/primesieve/} for a full
description.
@namespace primesieve
*/
var primesieve = (function() {
/**
Basket for the easier return of the functions of this module
@memberof primesieve
@private
*/
var Primesieve = {};
/**
Real size of the sieve in bits.
@memberof primesieve
@private
*/
var primelimit = 0;
/**
Buffer for the <code>ArrayBuffer</code>
@memberof primesieve
@private
*/
var buffer;
/**
The actual sieve.
@memberof primesieve
@private
*/
var primesieve;
/**
The guard limit of the primesieve.<br>
Currently set to one megabibyte, which can hold more than half a million
primes.
@memberof primesieve
@constant {number}
@default
@see primesieve.raiseLimit
*/
var primesizelimit = 0x800000; // 1 megabyte
/**
A [2, 3, 5, 7, 11] wheel for factoring
@memberof primesieve
@private
*/
var wheel = [
1, 2, 2, 4, 2, 4, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6,
8, 4, 2,
4, 2, 4, 14, 4, 6, 2, 10, 2, 6, 6, 4, 2, 4, 6, 2, 10, 2, 4,
2, 12,
10, 2, 4, 2, 4, 6, 2, 6, 4, 6, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8,
4, 2,
4, 6, 8, 6, 10, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 6,
10, 2,
10, 2, 4, 2, 4, 6, 8, 4, 2, 4, 12, 2, 6, 4, 2, 6, 4, 6, 12,
2, 4, 2,
4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 10, 2, 4, 6, 2, 6, 4, 2, 4, 2,
10, 2,
10, 2, 4, 6, 6, 2, 6, 6, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4,
2, 6,
4, 8, 6, 4, 6, 2, 4, 6, 8, 6, 4, 2, 10, 2, 6, 4, 2, 4, 2,
10, 2, 10,
2, 4, 2, 4, 8, 6, 4, 2, 4, 6, 6, 2, 6, 4, 8, 4, 6, 8, 4, 2,
4, 2, 4,
8, 6, 4, 6, 6, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10,
2, 10,
2, 6, 4, 6, 2, 6, 4, 2, 4, 6, 6, 8, 4, 2, 6, 10, 8, 4, 2, 4,
2, 4,
8, 10, 6, 2, 4, 8, 6, 6, 4, 2, 4, 6, 2, 6, 4, 6, 2, 10, 2,
10, 2, 4,
2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 6, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8,
6, 4, 8, 4, 6, 2, 6, 6, 4, 2, 4, 6, 8, 4, 2, 4, 2, 10, 2,
10, 2, 4,
2, 4, 6, 2, 10, 2, 4, 6, 8, 6, 4, 2, 6, 4, 6, 8, 4, 6, 2, 4,
8, 6,
4, 6, 2, 4, 6, 2, 6, 6, 4, 6, 6, 2, 6, 6, 4, 2, 10, 2, 10,
2, 4, 2,
4, 6, 2, 6, 4, 2, 10, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2,
12, 6,
4, 6, 2, 4, 6, 2, 12, 4, 2, 4, 8, 6, 4, 2, 4, 2, 10, 2, 10,
6, 2, 4,
6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 10, 6, 8, 6, 4, 2, 4, 8,
6, 4,
6, 2, 4, 6, 2, 6, 6, 6, 4, 6, 2, 6, 4, 2, 4, 2, 10, 12, 2,
4, 2, 10,
2, 6, 4, 2, 4, 6, 6, 2, 10, 2, 6, 4, 14, 4, 2, 4, 2, 4, 8,
6, 4, 6,
2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 12
];
/**
This sieve works with normal Arrays, too
@memberof primesieve
@private
*/
if (typeof Uint32Array === 'undefined') {
Uint32Array = Array;
ArrayBuffer = function() {
return 0;
};
}
/**
30*log(113)/113 see also {@link http://oeis.org/A209883 }
@memberof primesieve
@private
*/
var LN_113 = 1.25505871293247979696870747618124469168920275806274;
/**
Rosser, J. B. and Schoenfeld, L. <i>Approximate Formulas for Some
Functions of Prime Numbers.</i> Illinois J. Math. 6, 64-97, 1962
{@link http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.ijm/1255631807 }
@memberof primesieve
@param {number} limit upper limit of search
@return {number} Approximation of p(limit)
@see primesieve.approx_limit
@private
*/
var approx_pi = function(limit) {
// Math.ceil(5*x/(4*Math.log(x))) // would be more exact for large x
return Math.ceil((LN_113 * limit) / Math.log(limit)) + 2;
};
/**
Upper limit of pi(x). Uses expansion of li(x)-li(2)
@param {number} limit upper limit of search
@return {number} Approximation of p(limit)
@see primesieve.approx_pi
@memberof primesieve
@private
*/
var approx_limit = function(prime_pi) {
if (prime_pi < 10) {
return 30;
}
// see first term of expansion of li(x)-li(2)
return Math.ceil(prime_pi * (Math.log(prime_pi * Math.log(
prime_pi))));
};
/**
Checks if the given argument is a fitting integer
@memberof primesieve
@param {number} x an ECMAScript conforming number
@return {bool}
@private
*/
var isInt = function(x) {
if (isNaN(x)) {
return false;
}
if (x > -9007199254740992 && x <= 9007199254740992 && Math.floor(
x) == x) {
return true;
}
};
/**
Clear bit (set to zero) at given position
@memberof primesieve
@param {number} where position of the bit
@private
*/
var clear = function(where) {
primesieve[where >>> 5] &= ~((1 << (31 - (where & 31))));
};
/**
Get value of bit at given position
@memberof primesieve
@param {number} where position of the bit
@return {number} value of bit at given position
@private
*/
var get = function(where) {
return ((primesieve[where >>> 5] >>> ((31 - (where & 31)))) &
1);
};
/**
Get value next set (value = 1) bit from given position
@memberof primesieve
@param {number} where position of the start
@return {number} position of next set bit or -1
@private
*/
var nextset = function(from) {
while (from < primelimit && !get(from)) {
from++;
}
if (from === primelimit && !get(from)) {
return -1;
}
return from;
};
/**
Get value previous set (value = 1) bit from given position
@memberof primesieve
@param {number} where position of the start
@return {number} position of previous set bit or -1
@private
*/
var prevset = function(from) {
while (from >= 0 && !get(from)) {
from--;
}
if (from == 0 && !get(from)) {
return -1;
}
return from;
};
/**
Fill the primesieve.
@memberof primesieve
@param {number} n length of sieve. Maximum available prime is smaller or
equal to this argument
@private
*/
var fillsieve = function(n) {
var k, r, j;
n = n + 1;
primelimit = n - 1;
k = Math.ceil(n / 32);
if (typeof ArrayBuffer !== "function") {
buffer = new ArrayBuffer(k * 4);
} else {
buffer = k;
}
primesieve = new Uint32Array(buffer);
while (k--) {
primesieve[k] = 0xffffffff;
}
clear(0);
clear(1);
for (k = 4; k < n; k += 2) {
clear(k);
}
r = Math.floor(Math.sqrt(n));
k = 0;
while (k < n) {
k = nextset(k + 1);
if (k > r || k < 0) {
break;
}
for (j = k * k; j < n; j += 2 * k) {
clear(j);
}
}
};
/**
Error value for success/no error
@memberof primesieve
@constant {number}
@default
@private
*/
var E_SUCCESS = 0;
/**
Error value for "not an integer"
@memberof primesieve
@constant {number}
@default
@private
*/
var E_ARG_NO_INT = 1;
/**
Error value for "Argument given is too low"
@memberof primesieve
@constant {number}
@default
@private
*/
var E_ARG_TOO_LOW = 2;
/**
Error value for "Argument given is too high"
@memberof primesieve
@constant {number}
@default
@private
*/
var E_ARG_TOO_HIGH = 3;
/**
Error value for "above guard limit"
@memberof primesieve
@constant {number}
@default
@private
@see primesieve.raiseLimit
*/
var E_ABOVE_LIMIT = 4;
/**
Variable to hold error number
@alias error
@memberof primesieve
@constant {number}
@default
*/
Primesieve.error = 0;
/**
Function to convert an error number into a human readable string
@alias strerror
@memberof primesieve
@return {string} Summary of the error
*/
Primesieve.strerror = function() {
var strerrors = [
"Success",
"Argument not an integer",
"Argument too low",
"Argument too high",
"Prime wanted is higher than the limit ",
"Unknown error"
];
var e = Primesieve.error;
if (e == 0) {
return strerrors[0];
}
if (e < 0 || e > strerrors.length - 1) {
return strerrors[strerrors.length - 1];
}
if (e == E_ABOVE_LIMIT) {
return strerrors[E_ABOVE_LIMIT] + primesizelimit;
} else {
return strerrors[e];
}
};
/**
Checks if the given number is a small prime (must be in the sieve)<br>
For larger numbers see {@link primesieve.isPrime}
@alias isSmallPrime
@memberof primesieve
@param {number} prime positive small integer
@return {bool} or undefined in case of an error
@see primesieve.isPrime
*/
Primesieve.isSmallPrime = function(prime) {
if (!isInt(prime)) {
Primesieve.error = E_ARG_NO_INT;
return undefined;
} else if (prime < 2) {
Primesieve.error = E_ARG_TOO_LOW;
return undefined;
}
if (prime > primelimit) {
Primesieve.grow(prime + 100);
if (Primesieve.error == E_ABOVE_LIMIT) {
return undefined;
}
}
Primesieve.error = E_SUCCESS;
if (get(prime) == 1) {
return true;
}
return false;
};
/**
Checks if the given number is a prime.<br>
Might need a couple of seconds for larger primes.
@alias isPrime
@memberof primesieve
@param {number} prime positive integer < 2<sup><i>53</i></sup>
@return {bool} or undefined in case of an error
*/