Skip to content

Instantly share code, notes, and snippets.

@wdehaes
Last active September 30, 2016 01:22
Show Gist options
  • Save wdehaes/97817927824cf35434c4da33eec13f59 to your computer and use it in GitHub Desktop.
Save wdehaes/97817927824cf35434c4da33eec13f59 to your computer and use it in GitHub Desktop.
PrimeIt is a small command line program written in ruby that uses an improved version of the sieve of Eratosthenes to generate prime numbers based on the user's input, as well as prime factors
#PrimeIt is a command line program that uses an improved version of the sieve of Eratosthenes to generate prime numbers based on the user's input.
puts "Welcome to PrimeIt!"
def main_flow(input = nil)
until input == 0
puts "Pick any integer greater than 4, and the program will PrimeIt if for you. Press 0 to exit."
input = Integer(gets.chop) rescue false
until !!input and (input > 4 or input == 0) do
puts "Oops! I am afraid #{gets.chop} not an input that can be used by PrimeIt. Let's try again."
input = Integer(gets.chop) rescue false
end
if input == 0
puts "Thank you for using PrimeIt. Hope to see you again soon!"
else
ary = (3..input).step(2).to_a
primes = [2]
until ary.length == 0 do
element = ary.shift
element_stepper = element**2
comp =[]
until ary.last.nil? or element_stepper > ary.last
comp << element_stepper
element_stepper += element
end
ary = ary - comp
primes << element
end
primes = primes + ary
if primes.include? input
puts "Hoorah! #{input} is a prime number."
else
puts "Helas! #{input} is just a boring old number."
end
puts "There are #{primes.length} prime numbers smaller than or equal to #{input}."
puts "These are the following:"
puts primes.join(" ")
#prime factors
count_hash = Hash.new(0)
modulus = input
until modulus == 1
primes.each do |prime|
if modulus % prime == 0
modulus /= prime
count_hash[prime] += 1
break
end
end
end
factors = ""
count_hash.each do |key, value|
factors += "#{key}^#{value}x"
end
puts "#{input} can be written in prime factors as #{factors.chop}."
end
end
end
main_flow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment