How to Determine if a Number is Prime in Ruby?
In this article, we will discuss how to Determine if a Number is Prime and contains a specific value in ruby. We can determine if a Number is Prime through different methods. Let us study them in detail
Table of Content
- Determine if a Number is Prime using Prime Library Approach
- Determine if a Number is Prime using Loop Approach
- Determine if a Number is Prime using Sieve of Eratosthenes
Determine if a Number is Prime using the Prime Library Approach
Ruby provides an in-built Prime
library, which can be used to check if a number is prime using the prime?
method.
Syntax:
require ‘prime’
n.prime?
Example: In this example, we use prime? method from the prime library in ruby to check whether the number is prime or not
# Determine if a Number is Prime using Prime Library Approach
# Import the prime library
require 'prime'
# Define a method to check if a number is prime using the prime? method
def is_prime(n)
n.prime?
end
# Driver code
puts is_prime(17) # Output: true
puts is_prime(15) # Output: false
Output
true false
Determine if a Number is Prime using Loop Approach
In this method we iterate through each number from 2 up to the square root of the given number and checking if the number is divisible by any of those numbers and if it is not divisible than it is a prime number.
Example: In this example, we iterate through each number from 2 up to the square root of the given number and checking if the number is divisible by any of those numbers and if it is not divisible than it is a prime number..
def is_prime(n)
return false if n <= 1
return true if n == 2 || n == 3
return false if n % 2 == 0 || n % 3 == 0
i = 5
while i * i <= n
return false if n % i == 0 || n % (i + 2) == 0
i += 6
end
true
end
puts is_prime(17) # Output: true
puts is_prime(15) # Output: false
Output
true false
Determine if a Number is Prime using Sieve of Eratosthenes
The Sieve of Eratosthenes method generates all prime numbers up to a given number n
and then checks if the given number is present in the list of primes.
Example: In this example we use the sieve_of_eratosthenes
method generates all prime numbers up to n
, and then is_prime_sieve
checks if the given number n
is present in the list of primes.
def is_prime_sieve(n)
return false if n <= 1
primes = sieve_of_eratosthenes(n)
primes.include?(n)
end
def sieve_of_eratosthenes(n)
primes = []
sieve = Array.new(n + 1, true)
sieve[0] = sieve[1] = false
(2..Math.sqrt(n)).each do |i|
next unless sieve[i]
(i * i).step(n, i) { |j| sieve[j] = false }
end
sieve.each_with_index { |is_prime, i| primes << i if is_prime }
primes
end
puts is_prime_sieve(17) # Output: true
puts is_prime_sieve(15) # Output: false
Output
true false
Contact Us