Primes by Trial Division - valFORTH
30 September 2016
valFORTH has a built-in definition for INITIALIZE, a 1-based PICK, limited input line length, and no semantics for instantiating an infinite DO loop.
32767 CONSTANT MAXINT : CELLS 2* ; : #PRIME@ 2 + CELLS + ; : #PRIME >R DUP R> #PRIME@ @ ; : #PRIMES DUP 1 CELLS + @ ; : #PRIMES++ #PRIMES 1+ OVER 1 CELLS + ! ; : MAXPRIMES DUP @ ; : NOTPRIME DROP 0 ; : DIVIDES? MOD 0= ; : PINIT DUP >R HERE DUP R> 2 + CELLS ALLOT ROT SWAP ! 0 OVER 1 CELLS + ! ; : ISPRIME! DUP . CR OVER #PRIMES #PRIME@ ! #PRIMES++ ; : ISPRIME? OVER #PRIMES 0 DO I #PRIME 3 PICK SWAP DIVIDES? IF NOTPRIME LEAVE THEN LOOP ; : PRIMES PINIT CR 2 ISPRIME! MAXINT 3 DO I ISPRIME? IF ISPRIME! ELSE DROP THEN MAXPRIMES >R #PRIMES R> = IF LEAVE THEN LOOP ;