...

/

Solution: Finding Prime Numbers

Solution: Finding Prime Numbers

Go over the implementation of finding prime numbers smaller than 20.

We'll cover the following...

Solution

Press + to interact
array = []
(2..20).each do |num|
# check if num is a prime number or not
flag = true
(2..num - 1).each do |x| # check each possible divisor
if num % x == 0
flag = false # mark this has divisor
break # no point to check more - composite, moves on to next
end
end
if flag == true # the number has no divisors
array << num # add to prime number list
end
end
puts "Prime numbers (up to 20) are : #{array.join(', ')}"

Explanation

  • Line 4: Initially, flag is set to true and every number is considered a prime number.

  • Line 7: If the number has a divisor, then flag is set to false to indicate that it is not a ...