Created
June 14, 2017 13:49
-
-
Save wowdyaln/89c0752b84f0552811228c9af2298f6b to your computer and use it in GitHub Desktop.
Sieve of Sundaram algorithm
This file contains 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
##### Sieve of Sundaram algorithm | |
def prime_Sundaram(n) | |
n = n/2 | |
a = [] | |
a[n] = nil | |
t = (Math.sqrt(4+8*n)-2)/4 | |
u = 0 | |
r = [] | |
for i in 1..t do | |
u = (n-i)/(1+2*i) | |
for j in i..u do | |
a[i + j + 2*i*j] = true | |
end | |
end | |
for i in 0..n do | |
r.push(i*2+1) if !a[i] | |
end | |
puts r | |
end | |
# 測時間_2 | |
require 'benchmark' | |
Benchmark.bm do |x| | |
x.report do | |
prime_Sundaram(1000000) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment