mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-11-16 19:50:00 +01:00
Prime number ruby program implementation
This commit is contained in:
parent
c4725e9eb2
commit
0a745d673b
1 changed files with 38 additions and 0 deletions
38
maths/prime_number.rb
Normal file
38
maths/prime_number.rb
Normal file
|
@ -0,0 +1,38 @@
|
|||
# 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
|
||||
def is_prime_number(number)
|
||||
primeFlag = false
|
||||
if number>0
|
||||
if number == 1
|
||||
primeFlag = true
|
||||
else
|
||||
factors = 2;
|
||||
while factors.to_i <= number.to_i/2
|
||||
if number.to_i % factors.to_i==0
|
||||
primeFlag = true
|
||||
break
|
||||
end
|
||||
factors+=1
|
||||
end
|
||||
end
|
||||
else
|
||||
primeFlag = true
|
||||
end
|
||||
|
||||
if !primeFlag
|
||||
print "\nThe given number " + number.to_s + " is a Prime."
|
||||
else
|
||||
print "\nThe given number " + number.to_s + " is not a Prime."
|
||||
end
|
||||
end
|
||||
|
||||
# prime input
|
||||
is_prime_number(2)
|
||||
|
||||
# Non-prime input
|
||||
is_prime_number(20)
|
||||
|
||||
# Negative input
|
||||
is_prime_number(-21)
|
Loading…
Reference in a new issue