# My prime number generator might be slow?

Home Forums Forth Programming My prime number generator might be slow?

This topic contains 0 replies, has 1 voice, and was last updated by  Budsy 9 months, 3 weeks ago.

Viewing 1 post (of 1 total)
• Author
Posts
• #12395

Budsy
Participant

I like the new {: locals :} … So, here’s my prime numbers test. It is pretty performant on small output sets, but should it take 209 minutes to run the first 2,000,000 primes?? This algorithm may not be the most efficient:

\ FORTH prime numbers demo, by Bob Dickow
\ cobbled from some C code examples out there.
\ Usage: n .primes
\ Result: prints the first n prime numbers
\ tested on SwiftForth 3.7.1

CR

\ to execute, type ‘<n> .primes’ but this script auto executes with 20 .primes
\ displays 2, 3, 5, 7, … (nth prime)
\ compile + run time averages about 925 uSec on a Windows 10 Intel
\ Core i7-6700 4 GHz

: .primes ( n — ) \ n = how many primes to calculate and display
3 1 FALSE {: howmany candidate primecnt flg | prime_array :}
howmany CELLS ALLOCATE
0= if
TO prime_array
else
drop .” oooh… no memory?!” exit
then
prime_array howmany CELLS ERASE 2 prime_array !

BEGIN
primecnt 0 DO
candidate prime_array I CELLS + @ MOD 0= IF
\ Not a prime
2 +TO candidate
TRUE TO flg
LEAVE
THEN
LOOP
flg NOT IF
candidate prime_array primecnt CELLS + !
1 +TO primecnt
ELSE
FALSE TO flg
THEN
primecnt howmany >= UNTIL

\ print them all out:
howmany 0 DO
prime_array I CELLS + @ .
LOOP

prime_array FREE DROP
;

.( executing “20 .primes” ) CR
20 .primes \\ run the word

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.