The sieve of eratosthenes

J

NB. Sieve of Eratosthenes in J
NB. Written by Rob Hoelz

NB. To run, load this file into the J interpreter
NB. and call main <limit>

NB. NOTE: Although J has a built-in primes function,
NB.       I thought that'd be too cheap to use. =P

    mod =: dyad : 0
z =. x % y
z =. z - (<. z)
z * y
)

    removeMultiples =: dyad : 0
len =. # y
head =. {. y
tail =. }. y
if. len
  do.
  if. (head mod x)
    do. head , (x removeMultiples tail)
    else. x removeMultiples tail
  end.
  else. y
end.
)

    generatePrimes =: verb define
currPrime =. {. y
if. ((currPrime * currPrime) <: {: y)
  do. currPrime , (generatePrimes (currPrime removeMultiples (}. y)))
  else. y
end.
)
    main =: verb define
generatePrimes ((2 }. i. y) , y)
)

back to Eratosthenes page

stats

It is Saturday May 17, 2008 11:01 am
This page served 641 times
This page last modified: April 14, 2008 11:28 am
Your IP address is: 38.103.63.17
You are browsing using: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
You are browsing from: United States.
badcomputer.org's uptime: 11:01:44 up 23 days, 11:43, 0 users, load average: 0.26, 0.14, 0.05

local

home | unix stuff | dir2ogg | sneetchalizer | wmainfo | q&d guide to permissions | q&d guide to tar and gzip | code | MS rant | browser shootout | linux & iAudio X5 | photos | music | programming poetry | sieve of Eratosthenes | plea | rain | suffer | archive | about | recipes | compaqr3000 | sitemap

search

Google

credits

hacker emblem

This page, and all pages on this site were created and are maintained by Darren Kirby using valid XHTML 1.0 and CSS, and are ©copyright 2002 - 2008. The Penguin image was created by Tukka, and is used by permission. Inspiration for the look of this site was provided by Eric A. Meyer's CSS gallery. This website runs on Gentoo Linux. It is served by Apache. PHP and MySQL hold together the backend.

advertisement