Created
November 13, 2012 18:32
-
-
Save clowder/4067513 to your computer and use it in GitHub Desktop.
Prime multiplication table
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
#!/usr/bin/env ruby | |
require 'open-uri' | |
how_many = ARGV.pop || 10 | |
how_many = how_many.to_i | |
module Prime | |
def self.take(count) | |
search_space = 2..count**2 | |
search_space.select { |x| is_prime?(x) }.take(count) | |
end | |
def self.is_prime?(number) | |
(2..(number**0.5).to_i).select { |divisor| number % divisor == 0 }.empty? | |
end | |
end | |
first_row = [1] + Prime.take(how_many) | |
pad_to = (first_row.last**2).to_s.size | |
comp = first_row.flat_map { |x| first_row.map { |y| x*y } }.map { |z| (z==1 ? "" : z.to_s).rjust(pad_to) } | |
comp.each_slice(how_many + 1) do |line| | |
puts line.join(" | ") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment