How to know a number is prime without a built-in method in Ruby
Overview
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:
Algorithm
The algorithm to check whether or not a number is prime is as follows:
# create first countercounter1 = 0# check if number is zeroif (number==0)puts "0 is not a prime number"else# create counter 2counter2 = 2while(counter2 < number)if (number % counter2==0)counter1 += 1endcounter2 += 1endendif counter1 > 1puts "#{number} is not a prime number"elseputs "#{number} is a prime number"end
Check if a number is prime in Ruby
Explanation
- We first check if the number is zero. If it is, we know it is not a prime number.
- We also check if the number is divisible by two.
- Then, we check if the number is greater than 1.
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.
Example
# create a function to check# if a number is prime or notdef checkIfPrime(number)# create first countercounter1 = 0# check if number is zeroif (number==0)puts "0 is not a prime number"else# create counter 2counter2 = 2while(counter2 < number)if (number % counter2==0)counter1 += 1endcounter2 += 1endendif counter1 > 1puts "#{number} is not a prime number"elseputs "#{number} is a prime number"endend# create some numbersno1 = 12no2 = 3no3 = 7no4 = 127no5 = 91# check if the numbers are prime numbersputs checkIfPrime(no1)puts checkIfPrime(no2)puts checkIfPrime(no3)puts checkIfPrime(no4)puts checkIfPrime(no5)
Explanation
- Line 3: We create a method called
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. - Lines 28–32: We create some numbers to check if they are prime or not.
- Lines 35–39: We use the
checkIfPrime()function we created to check if the numbers are prime numbers.