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 notflag = true(2..num - 1).each do |x| # check each possible divisorif num % x == 0flag = false # mark this has divisorbreak # no point to check more - composite, moves on to nextendendif flag == true # the number has no divisorsarray << num # add to prime number listendendputs "Prime numbers (up to 20) are : #{array.join(', ')}"
Explanation
Line 4: Initially,
flag
is set totrue
and every number is considered a prime number.Line 7: If the number has a divisor, then
flag
is set tofalse
to indicate that it is not a ...