A prime number is a number divisible only by itself
and 1
without a remainder. Examples include 2, 3, 5, 7, 11, 13, and so on.
In Ruby, we can check whether or not a number is prime by using the logic in the syntax below:
The algorithm to check whether or not a number is prime is as follows:
# create first counter counter1 = 0 # check if number is zero if (number==0) puts "0 is not a prime number" else # create counter 2 counter2 = 2 while(counter2 < number) if (number % counter2==0) counter1 += 1 end counter2 += 1 end end if counter1 > 1 puts "#{number} is not a prime number" else puts "#{number} is a prime number" end
With all these, we can check if a number is a prime.
With the algorithm above, we get an output to the console telling us whether or not the number specified is a prime number.
# create a function to check # if a number is prime or not def checkIfPrime(number) # create first counter counter1 = 0 # check if number is zero if (number==0) puts "0 is not a prime number" else # create counter 2 counter2 = 2 while(counter2 < number) if (number % counter2==0) counter1 += 1 end counter2 += 1 end end if counter1 > 1 puts "#{number} is not a prime number" else puts "#{number} is a prime number" end end # create some numbers no1 = 12 no2 = 3 no3 = 7 no4 = 127 no5 = 91 # check if the numbers are prime numbers puts checkIfPrime(no1) puts checkIfPrime(no2) puts checkIfPrime(no3) puts checkIfPrime(no4) puts checkIfPrime(no5)
checkIfPrime()
that takes a single parameter. It uses the logic we previously implemented to check if a number is prime or not. It then prints the result to the console.checkIfPrime()
function we created to check if the numbers are prime numbers.RELATED TAGS
CONTRIBUTOR
View all Courses