Last active
August 29, 2015 14:08
-
-
Save zipcode/2aa84d7ea7be3e6098b3 to your computer and use it in GitHub Desktop.
Corecursive primes
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
divisor = (x) -> | |
c = 0 | |
r = Math.sqrt(x) | |
p = primes(c) | |
while p <= r | |
return p if x % p == 0 | |
p = primes(++c) | |
x | |
isPrime = (x) -> divisor(x) == x | |
divisors = (x) -> | |
r = [] | |
while x > 1 | |
d = divisor(x) | |
r.push d | |
x = x/d | |
r | |
primes = (-> | |
store = [2] | |
(x) -> | |
while x >= store.length | |
next = store[store.length-1] + 1 | |
until isPrime next | |
next++ | |
store.push next | |
store[x] | |
)() | |
show = (x) -> | |
console.log x, divisors x | |
show 1007 | |
show 1009 | |
show 2048 | |
show 2049 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment