10:24 PM

Prime Numbers by Ruby

My Works, by Wei.
def pn(max)
  m = (max + 1) / 2
  $pn = Array.new(max)
  for i in 1..m
    $pn[i] = (i << 1) - 1
  end
  n = m + 1
  for p in 2..m
    next unless $pn[p]
    q = p + $pn[p]
    while q < n
      $pn[q] = nil
      q += $pn[p]
    end
  end
  $pn.compact!
  $pn[0] = 2
  return $pn
end
 
t1=Time.now
pn(1_000_000)
t2=Time.now
p $pn[0..23]
p t2-t1
loop{eval(gets) rescue p $!}

This method is probably the most efficiency method.

To list the prime numbers that less than 1 million just use 2.532s.

Back Top

Responses to “Prime Numbers by Ruby”

Leave a Reply

Back Top

Note: Commenter is allowed to use '@User:' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC:'(exclude ') will automatically send your comment to ABC.