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
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
Contact Us