Related Tags

ruby

# How to know a number is prime without a built-in method in Ruby

okwudili onyejiaku

### 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 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
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 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)
Check if a number is a prime number in Ruby

### 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.

RELATED TAGS

ruby

CONTRIBUTOR

okwudili onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time