Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Created May 22, 2019 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbloom7/a0930f2080746afff7a6a24c2eccac6e to your computer and use it in GitHub Desktop.
Save chrisbloom7/a0930f2080746afff7a6a24c2eccac6e to your computer and use it in GitHub Desktop.
Detecting prime numbers in Ruby
# A prime is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers
def prime?(int)
# A prime is a natural number greater than 1...
return false if int < 2
# Is _int_ evenly divisible by any number 2 -> int-1?
(2..(int - 1)).each do |divisor|
return false if int % divisor == 0
end
return true
end
(1..100).each do |int|
puts int if prime?(int)
end
# OR, using the standard Prime class
require "prime"
(1..100).each do |int|
puts int if Prime.prime?(int)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment