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-03-28 19:15:12 +02:00
|
|
|
if number <= 1
|
|
|
|
non_prime_flag = true
|
|
|
|
elsif number == 2
|
|
|
|
non_prime_flag = false
|
|
|
|
elsif number % 2 == 0
|
2021-03-28 18:55:40 +02:00
|
|
|
non_prime_flag = true
|
2021-03-28 19:15:12 +02:00
|
|
|
else
|
|
|
|
non_prime_flag = (2..Math.sqrt(number)).any? { |i| number % i == 0 }
|
2021-03-27 08:38:46 +01:00
|
|
|
end
|
|
|
|
|
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)
|