Skip to content

Instantly share code, notes, and snippets.

@jrallison
Created May 3, 2009 19:52
Show Gist options
  • Save jrallison/106136 to your computer and use it in GitHub Desktop.
Save jrallison/106136 to your computer and use it in GitHub Desktop.
def first_n_primes(n)
return [] if n <= 0
@primes ||= [2]
x = @primes.last + 1
until @primes.length >= n
prime = true
@primes.each do |p|
if x % p == 0
prime = false
break
end
end
@primes << x if prime
x += 1
end
@primes[0..n-1]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment