Created
May 22, 2019 16:31
-
-
Save chrisbloom7/a0930f2080746afff7a6a24c2eccac6e to your computer and use it in GitHub Desktop.
Detecting prime numbers in Ruby
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
# 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