Created
January 19, 2011 21:42
-
-
Save alxhill/786927 to your computer and use it in GitHub Desktop.
From @jamierumbelow - a simple Ruby script to get x number of primes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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