Skip to content

Instantly share code, notes, and snippets.

@zipcode
Last active August 29, 2015 14:08
Show Gist options
  • Save zipcode/2aa84d7ea7be3e6098b3 to your computer and use it in GitHub Desktop.
Save zipcode/2aa84d7ea7be3e6098b3 to your computer and use it in GitHub Desktop.
Corecursive primes
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