DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Nsieve For Ruby

10.11.2007
| 3374 views |
  • submit to reddit
        From: <a href="http://shootout.alioth.debian.org/debian/benchmark.php?test=nsievebits&lang=ruby&id=2">The Great Computer Language Shootout: nsieve-bits Ruby</a>
Author: Glenn Parker


CharExponent = 3
BitsPerChar = 1 << CharExponent
LowMask = BitsPerChar - 1

def sieve(m)
  ret = []
  items = "\xFF" * ((m / BitsPerChar) + 1)
  masks = ""
  BitsPerChar.times do |b|
    masks << (1 << b).chr
  end

  count = 0
  pmax = m - 1
  2.step(pmax, 1) do |p|
    if items[p >> CharExponent][p & LowMask] == 1
      ret << p
      count += 1
      p.step(pmax, p) do |mult|
	a = mult >> CharExponent
	b = mult & LowMask
	items[a] -= masks[b] if items[a][b] != 0
        #p items
      end
    end
  end
  #count
  ret
end

n = (ARGV[0] || 2).to_i
n.step(n - 2, -1) do |exponent|
  break if exponent < 0
  m = 2 ** exponent * 10_000
  primes = sieve(m)
  count = primes.size
  puts
  printf "Primes up to %8d %8d\n", m, count
  puts "last ten primes: #{primes[-10..-1].join(' ')}"
  puts
end

    

Comments

Snippets Manager replied on Sun, 2009/01/11 - 6:16pm

online gambling can be fun. Play poker online and win with these free poker odds calculators

poker odds calculator

win at online poker

calculator poker

Blackjack Strategy