Skip to content

Instantly share code, notes, and snippets.

@jamierumbelow
Created December 29, 2010 23:32
Show Gist options
  • Save jamierumbelow/759217 to your computer and use it in GitHub Desktop.
Save jamierumbelow/759217 to your computer and use it in GitHub Desktop.
A quick prime number finder
# 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