Primes by Trial Division - Forth

29 September 2016

I can't promise this is classically idiomatic Forth.

For Forth-83 only,

: cells  2* ;

For SPARCv8 OpenBoot only,

: cells  4 * ;

All platforms:

: #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= ;
: initialize 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 2 pick swap divides?
      if notprime leave then
  loop ;

: primes
  decimal initialize cr 2 isprime! 3 dup do
    i isprime? if isprime! else drop then
    maxprimes >r #primes r> = if leave then
  loop ;

The performance of OpenBoot Forth is more closely tied to how fast the console can be updated than it is to processor speed. You can see this most clearly with Macintosh Open Firmware if you execute words before executing 100 primes. As the vocabulary scrolls off the top of the screen, new results appear more and more quickly.

Typewritten Software • bear@typewritten.org • Edmonds, WA 98026

Museum

Home

Lab Overview

Retrotechnology Articles

⇒ Primes Benchmark Source

Media Vault

Software Library

Restoration Projects

Artifacts Sought

Related Articles

Primes Benchmark Results

Other Forths

Forth

GraFORTH

HCCS FORTH

HiSoft FORTH

JForth

valFORTH

VIC FORTH