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.

Ruby
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


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

Similar Reads

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

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

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

Contact Us