Instructions
Create a function first_n_primes that returns the first N prime numbers.
Use lazy enumerators to avoid computing unnecessary values:
ruby
(1..).lazy # Infinite sequence
.select { |n| condition } # Filter lazily
.take(5) # Take only 5
.to_a # Convert to array
The (1..) creates an infinite range. Without lazy, this would
run forever! With lazy, only the needed values are computed.
A prime number is greater than 1 and divisible only by 1 and itself.
Hints:
- Use (2..).lazy to start from 2
- Create a prime? helper or inline check
- A number n is prime if (2...n).none? { |i| n % i == 0 }
Your Code
def first_n_primes(n)
prime? = ->(num) { num > 1 && (2...num).none? { |i| num % i == 0 } }
(2..).lazy
.select { |num| prime?.call(num) }
.take(n)
.to_a
end
RSpec.describe "first_n_primes" do
it "returns first 5 primes" do
expect(first_n_primes(5)).to eq([2, 3, 5, 7, 11])
end
it "returns first 10 primes" do
expect(first_n_primes(10)).to eq([2, 3, 5, 7, 11, 13, 17, 19, 23, 29])
end
it "returns empty for 0" do
expect(first_n_primes(0)).to eq([])
end
it "returns single prime for 1" do
expect(first_n_primes(1)).to eq([2])
end
end
Results
Click "Run Tests" to see results