Last active
October 10, 2020 14:04
-
-
Save countingpine/4af235fd5e3c0f278f31e42fe5b6bed6 to your computer and use it in GitHub Desktop.
Simple prime sieve written in FreeBASIC. It outputs the number of primes found, and the time it took. Uses around 512 MB of memory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'' Simple prime sieve written in FreeBASIC. Compiles a table of all the primes under 2^32 (configurable). | |
'' It outputs the number of primes found (should be 203280221 under 2^32), and the time it took (roughly 2-3 mins on my old-ish PC). | |
'' It uses around 512 MB of memory (one bit for each odd number in the range). | |
#define MAX 4294967295 | |
type LUT_INT as uinteger | |
#ASSERT cast(LUT_INT, MAX) = MAX | |
const LUT_INTBITS = sizeof(LUT_INT) * 8 | |
dim shared as LUT_INT composite_lut(0 to MAX\LUT_INTBITS\2) | |
#define LUTPOS(n) ((n) \ (2 * LUT_INTBITS)) | |
#define LUTBIT(n) (((n) \ 2) mod LUT_INTBITS) | |
#define IS_COMPOSITE(n) BIT(composite_lut(LUTPOS(n)), LUTBIT(n)) | |
#define IS_PRIME(n) (not IS_COMPOSITE(n)) | |
#define SET_COMPOSITE(n) composite_lut(LUTPOS(n)) or= 1u shl LUTBIT(n) | |
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' | |
var start_time = timer | |
dim as uinteger i = 3, j | |
dim as integer primecount = 1 '' count 2 separately | |
do | |
if IS_PRIME(i) then | |
primecount += 1 | |
if i <= sqr(MAX) then | |
'print i & !"\r"; | |
j = i*i | |
do | |
SET_COMPOSITE(j) | |
if j > MAX-i*2 then exit do | |
j += i*2 | |
loop | |
end if | |
end if | |
if i > MAX-2 then exit do | |
i += 2 | |
loop | |
print using "Number of primes <= &: &"; MAX; primecount | |
print csng(timer-start_time) & " seconds" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment