Last active
December 13, 2015 21:08
-
-
Save Janiczek/4974905 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
| 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