math.primes.erato: Fix off-by-one error

The sieve bit vector deals with numbers in chunks of 30. Therefore,
the number 90 (say) is the 91st 'element' of the vector. Each byte
deals with some range {0,1,...,29}+30n so to have the number 90, you
need four bytes.

Rather pleasingly, I bumped into this bug and it reduced to the
incantation:
  2010 2010 sieve marked-prime?
db4
Rupert Swarbrick 2010-10-21 11:49:13 +01:00 committed by Samuel Tardieu
parent 974f4cfda4
commit cd28c7a219
2 changed files with 8 additions and 2 deletions

View File

@ -1,4 +1,5 @@
USING: byte-arrays math math.bitwise math.primes.erato sequences tools.test ; USING: kernel byte-arrays sequences tools.test ;
USING: math math.bitwise math.ranges math.primes.erato ;
[ B{ 255 251 247 126 } ] [ 100 sieve ] unit-test [ B{ 255 251 247 126 } ] [ 100 sieve ] unit-test
[ 1 100 sieve marked-prime? ] [ bounds-error? ] must-fail-with [ 1 100 sieve marked-prime? ] [ bounds-error? ] must-fail-with
@ -8,3 +9,8 @@ USING: byte-arrays math math.bitwise math.primes.erato sequences tools.test ;
! There are 25997 primes below 300000. 1 must be removed and 3 5 7 added. ! There are 25997 primes below 300000. 1 must be removed and 3 5 7 added.
[ 25997 ] [ 299999 sieve [ bit-count ] map-sum 2 + ] unit-test [ 25997 ] [ 299999 sieve [ bit-count ] map-sum 2 + ] unit-test
! Check sieve array length logic by making sure we get the right
! end-point for numbers with all possibilities mod 30. If something
! were to go wrong, we'd get a bounds-error.
[ ] [ 2 100 [a,b] [ dup sieve marked-prime? drop ] each ] unit-test

View File

@ -28,7 +28,7 @@ CONSTANT: masks B{ 0 128 0 0 0 0 0 64 0 0 0 32 0 16 0 0 0 8 0 4 0 0 0 2 0 0 0 0
2drop 2drop
] if ; ] if ;
: init-sieve ( n -- arr ) 29 + 30 /i 255 <array> >byte-array ; : init-sieve ( n -- arr ) 30 /i 1 + 255 <array> >byte-array ;
PRIVATE> PRIVATE>