Skip to content

Instantly share code, notes, and snippets.

@alxhill
Created January 19, 2011 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxhill/786927 to your computer and use it in GitHub Desktop.
Save alxhill/786927 to your computer and use it in GitHub Desktop.
From @jamierumbelow - a simple Ruby script to get x number of primes.
# Prime number finder
# Usage: 20.primes, 100.primes
module GetAllPrimeNumbers
def primes
# Get all numbers from 0 to the current number as an array
nums = (0 .. self).to_a
# We know 0 and 1 can't be prime
nums[0] = nums[1] = nil
# Loop through each number
nums.each do |n|
# Ignore the nils
next if n.nil?
# Remove any multiples of 2, and bingo
(n * n).step(self, n) { |m| nums[m] = nil }
end
# Finally, get rid of the nils and return
nums.compact
end
end
# An example of a great feature of Ruby - Monkey patching. Allows you
# to add/overwrite methods dynamically on any classes; including built-in
# data types (so strings, numbers, whatever).
class Fixnum
include GetAllPrimeNumbers
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment