2021-03-27 13:08:46 +05:30
|
|
|
# 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 22:25:40 +05:30
|
|
|
def prime_number(number)
|
2021-03-28 22:45:12 +05:30
|
|
|
if number <= 1
|
|
|
|
non_prime_flag = true
|
|
|
|
elsif number == 2
|
|
|
|
non_prime_flag = false
|
|
|
|
elsif number % 2 == 0
|
2021-03-28 22:25:40 +05:30
|
|
|
non_prime_flag = true
|
2021-03-28 22:45:12 +05:30
|
|
|
else
|
|
|
|
non_prime_flag = (2..Math.sqrt(number)).any? { |i| number % i == 0 }
|
2021-03-27 13:08:46 +05:30
|
|
|
end
|
|
|
|
|
2021-03-28 22:25:40 +05:30
|
|
|
if !non_prime_flag
|
2021-03-28 15:25:00 +05:30
|
|
|
puts "The given number #{number} is a Prime."
|
2021-03-27 13:08:46 +05:30
|
|
|
else
|
2021-03-28 15:25:00 +05:30
|
|
|
puts "The given number #{number} is not a Prime."
|
2021-03-27 13:08:46 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-03-28 22:25:40 +05:30
|
|
|
# Non-prime input
|
|
|
|
prime_number(1)
|
|
|
|
|
2021-03-27 13:08:46 +05:30
|
|
|
# prime input
|
2021-03-28 22:25:40 +05:30
|
|
|
# Number 2 is an even prime number
|
|
|
|
prime_number(2)
|
2021-03-27 13:08:46 +05:30
|
|
|
|
|
|
|
# Non-prime input
|
2021-03-28 22:25:40 +05:30
|
|
|
prime_number(20)
|
2021-03-27 13:08:46 +05:30
|
|
|
|
|
|
|
# Negative input
|
2021-03-28 22:25:40 +05:30
|
|
|
prime_number(-21)
|