2021-03-27 08:38:46 +01:00
|
|
|
# A ruby program to check a given number is prime or not
|
|
|
|
# Mathematical explanation: A number which has only 2 factors i.e., 1 (one) and itself
|
|
|
|
|
|
|
|
# Prime number check function
|
2021-03-28 18:55:40 +02:00
|
|
|
def prime_number(number)
|
2021-09-03 22:24:58 +02:00
|
|
|
non_prime_flag = if number <= 1
|
|
|
|
true
|
|
|
|
elsif number == 2
|
|
|
|
false
|
|
|
|
elsif number.even?
|
|
|
|
true
|
|
|
|
else
|
|
|
|
(2..Math.sqrt(number)).any? { |i| number % i == 0 }
|
|
|
|
end
|
2021-03-27 08:38:46 +01:00
|
|
|
|
2021-03-28 18:55:40 +02:00
|
|
|
if !non_prime_flag
|
2021-03-28 11:55:00 +02:00
|
|
|
puts "The given number #{number} is a Prime."
|
2021-03-27 08:38:46 +01:00
|
|
|
else
|
2021-03-28 11:55:00 +02:00
|
|
|
puts "The given number #{number} is not a Prime."
|
2021-03-27 08:38:46 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-03-28 18:55:40 +02:00
|
|
|
# Non-prime input
|
|
|
|
prime_number(1)
|
|
|
|
|
2021-03-27 08:38:46 +01:00
|
|
|
# prime input
|
2021-03-28 18:55:40 +02:00
|
|
|
# Number 2 is an even prime number
|
|
|
|
prime_number(2)
|
2021-03-27 08:38:46 +01:00
|
|
|
|
|
|
|
# Non-prime input
|
2021-03-28 18:55:40 +02:00
|
|
|
prime_number(20)
|
2021-03-27 08:38:46 +01:00
|
|
|
|
|
|
|
# Negative input
|
2021-03-28 18:55:40 +02:00
|
|
|
prime_number(-21)
|