in reply to Sieve of Eratosthenes Golf?

It probably won't win the golf, but it will go a lot higher than most. It'll handle upto 1,000,000,000 if you have 1 GB of ram.
sub f{ #23456789 123456789 123456789 123456789 123456789 123456789 $_=1x$_[0];for$n(1..sqrt$_[0]){m[^.{$n}.]g;s[\G(.{$n}).][${1}0]g;} } f(pop); ++$i and $1 and print $i while m[(.)]g;

And this one will go eight times higher in the same space, and should be relatively quick.
sub f{ $x="\xff"x$_[0];for(2..$_[0]){$n=$_;vec($x,$n,1)=0 while($n+=$_)<$_[0] +;} } f( $ARGV[0]); vec$x,$_,1 and print $_ for 1..$ARGV[0];

You could double that by not storing the evens,


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco.
Rule 1 has a caveat! -- Who broke the cabal?

Replies are listed 'Best First'.
Re^2: Sieve of Eratosthenes Golf?
by Cody Pendant (Prior) on Apr 07, 2005 at 07:17 UTC
    I don't understand those at all really, but the second one did a million in about a minute, so not bad at all. It did tell me that a million was a prime number though...


    ($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
    =~y~b-v~a-z~s; print
      It did tell me that a million was a prime number though...

      Due to golfing it, it doesn't handle the very last number correctly.

      I don't understand those at all really,

      They both work in essentially the same way. The first one creates a string of $limit '1's. It then uses a regex to scan the string substituting '0's for '1's, for all the multiples. It then scans the string, incrementing a counter, looking for the remaining '1's and prints out the counter when it finds a '1'. It just uses the big string as a tally stick and 'crosses off' all the multiples.

      The second one does the same thing, but uses vec, and bits instead of bytes, to represent the tally stick.

      By avoiding building big lists/arrays, it allows you to go 30/250 or so times higher.

      If you're not golfing, it is easy to omit the even bytes/bits and therebye double the range again.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco.
      Rule 1 has a caveat! -- Who broke the cabal?