Skip to content

Commit a8c5f06

Browse files
author
Ary Borenszweig
committed
Merge pull request crystal-lang#751 from mrjbq7/sieve
adding the sieve of eratosthenes example.
2 parents 1d1c67b + 29e1680 commit a8c5f06

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

samples/sieve.cr

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Compute prime numbers up to 100 with the Sieve of Eratosthenes
2+
max = 100
3+
4+
sieve = Array.new(max + 1, true)
5+
sieve[0] = false
6+
sieve[1] = false
7+
8+
2.step(Math.sqrt(max)) do |i|
9+
if sieve[i]
10+
(i * i).step(max, i) do |j|
11+
sieve[j] = false
12+
end
13+
end
14+
end
15+
16+
sieve.each_with_index do |prime, number|
17+
if prime
18+
puts number
19+
end
20+
end

0 commit comments

Comments
 (0)