Ruby Program to Check Prime Number
def prime?(n); return false if n <= 1; (2..Math.sqrt(n).to_i).none? { |i| n % i == 0 }; end which returns true if n is prime and false otherwise.Examples
How to Think About It
Algorithm
Code
def prime?(n) return false if n <= 1 (2..Math.sqrt(n).to_i).none? { |i| n % i == 0 } end print "Enter a number: " num = gets.to_i if prime?(num) puts "#{num} is a prime number" else puts "#{num} is not a prime number" end
Dry Run
Let's trace the number 7 through the code
Check if 7 <= 1
7 is greater than 1, so continue
Calculate square root of 7
Math.sqrt(7) ≈ 2.645, so check divisors 2 to 2
Check if 7 % 2 == 0
7 % 2 = 1, not zero, so no divisor found
No divisors found, return true
7 is prime
| i | 7 % i | Divides evenly? |
|---|---|---|
| 2 | 1 | No |
Why This Works
Step 1: Exclude numbers <= 1
Numbers less than or equal to 1 are not prime by definition, so we return false immediately.
Step 2: Check divisors up to square root
A larger divisor would pair with a smaller one already checked, so checking up to the square root is enough.
Step 3: Return true if no divisors found
If no number divides n evenly, n has no factors other than 1 and itself, so it is prime.
Alternative Approaches
def prime?(n) return false if n <= 1 (2..Math.sqrt(n).to_i).each do |i| return false if n % i == 0 end true end
require 'prime' print "Enter a number: " num = gets.to_i if Prime.prime?(num) puts "#{num} is a prime number" else puts "#{num} is not a prime number" end
Complexity: O(√n) time, O(1) space
Time Complexity
The program checks divisors only up to the square root of n, so it runs in O(√n) time.
Space Complexity
The program uses a constant amount of extra space, O(1), as it only stores a few variables.
Which Approach is Fastest?
Using early return in a loop is slightly faster than using none? because it stops checking as soon as a divisor is found. Using Ruby's Prime class is convenient but may have overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Range with none? | O(√n) | O(1) | Simple and readable code |
| Loop with early return | O(√n) | O(1) | Faster for large numbers |
| Ruby Prime class | Depends on implementation | O(1) | Quick use with built-in methods |