Skip to content

Instantly share code, notes, and snippets.

@robyurkowski
Forked from anonymous/PrimeNoV2
Created September 29, 2011 19:17
Show Gist options
  • Save robyurkowski/1251661 to your computer and use it in GitHub Desktop.
Save robyurkowski/1251661 to your computer and use it in GitHub Desktop.
Prime number checker
#retrive a number between 1 and another value - varUpper
# R: In Ruby, we strive for legibility. varUpper is an okay variable name, but an even better one would be upper_limit (var is implied by the fact it's a var, and Upper isn't clear as to what it refers).
upper_limit = 100
# R: This is one way to do a string, with single quotes. There are also a couple of alternatives, but the primary one is this:
# Double quotes let you put variables in a string in between #{} -- this will also automatically call .to_s.
puts "Welcome to Keith's Prime Number Checker. Please enter an integer between one and #{upper_limit}"
# R: We'll name this something more verbose, too:
potential_prime = gets.chomp.to_i
if (potential_prime <= upper_limit) and (potential_prime > 1)
# R: Ruby uses two spaces instead of tabs.
puts 'Thank you. The number you have entered is ' + varTest.to_s + '.'
else
while (potential_prime > upper_limit) or (potential_prime <= 1)
puts 'The number you have entered is not valid. Please enter another number.'
potential_prime = gets.chomp.to_i
end
end
puts potential_prime.to_s + ' will now be checked to see if it is a prime.'
#test
divisor = 2
mod_result = 1
is_prime = true
# R: From 2 up to potential prime / 2 + 1, do as i...
divisor.upto(potential_prime / 2 + 1) do |i|
is_prime = false if (potential_prime % i == 0)
end
if is_prime
puts "Congratulations! #{potential_prime} is a prime number!"
else
puts "Test completed. #{potential_prime} is not a prime number."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment