Skip to content

Instantly share code, notes, and snippets.

@Janiczek Janiczek/sieve_sundaram
Last active Dec 13, 2015

Embed
What would you like to do?
sieve_sundaram = (limit) ->
start = 4
half = limit/2
numbers = (n for n in [3...limit+1] by 2)
steps = numbers[..] # copy of numbers
callback = (start_and_nums,step) ->
start = start_and_nums[0]
nums = start_and_nums[1..]
if start > half
result = (n for n in nums when n > 0)
result.unshift start
return result
# We can't stop iterating inside the reduce() although we'd like to right now.
# Also, we slice the first element every time our function gets called,
# so we'll put it back here for now. We'll deal with it after reduce() finishes.
# Also, we mustn't forget about the 2!
idxs = (idx-1 for idx in [start...half] by step)
new_nums = ((if i in idxs then 0 else num) for num,i in nums)
new_start = start + 2 * (step + 1)
new_start_and_nums = new_nums[..]
new_start_and_nums.unshift new_start
return new_start_and_nums
start_and_nums = numbers[..]
start_and_nums.unshift start
result = (steps.reduce(callback,start_and_nums))
result.shift()
result.unshift 2
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.