Created
December 14, 2025 18:13
-
-
Save dudo/85f2f207e0f7de747adea8cbc63dfd5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def sieve(limit) | |
| return [] if limit < 2 | |
| is_prime = Array.new(limit + 1) do |i| | |
| i == 2 || i.odd? # mark 2 and all odd numbers true, everything else false | |
| end | |
| max = Math.sqrt(limit).floor | |
| (3..max).step(2) do |p| | |
| next unless is_prime[p] | |
| (p * p).step(limit, 2 * p) do |multiple| | |
| is_prime[multiple] = false | |
| end | |
| end | |
| [2] + (3..limit).step(2).select { |n| is_prime[n] } | |
| end | |
| puts sieve(30).inspect | |
| # => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment