Skip to content

Instantly share code, notes, and snippets.

@oieioi
Last active August 29, 2015 14:01
Show Gist options
  • Save oieioi/17a0d1c1ceb03b0eca05 to your computer and use it in GitHub Desktop.
Save oieioi/17a0d1c1ceb03b0eca05 to your computer and use it in GitHub Desktop.
prime?
isPrime = (num)->
# 整数チェック
if Math.floor(num) isnt num then return false
if num < 2 then return false
if num is 2 then return true
# 偶数は除いてチェック
if num % 2 is 0 then return false
for n in [3..Math.floor num/2] by 2 when num % n is 0 then return false
# 素数発見
true
getPrimes = (range) -> for num in [0...range] when isPrime num then num
module.exports =
isPrime: isPrime
getPrimes : getPrimes
# test
do ->
console.time 'test'
console.assert getPrimes(100000).length is 9592 , "getPrimes(10000).length 9592 is #{getPrimes(100000).length} "
console.assert isPrime(2.2) is false , 'isPrime(2.2) is false '
console.assert isPrime(1) is false , 'isPrime(1) is false '
console.assert isPrime(2) is true , 'isPrime(2) is true '
console.assert isPrime(3) is true , 'isPrime(3) is true '
console.assert isPrime(4) is false , 'isPrime(4) is false '
console.assert isPrime(5) is true , 'isPrime(5) is true '
console.assert isPrime(6) is false , 'isPrime(6) is false '
console.assert isPrime(7) is true , 'isPrime(7) is true '
console.assert isPrime(8) is false , 'isPrime(8) is false '
console.assert isPrime(9) is false , 'isPrime(9) is false '
console.assert isPrime(10) is false , 'isPrime(10) is false '
console.assert isPrime(983) is true , 'isPrime(983) is true '
console.assert isPrime(6473) is true , 'isPrime(6473) is true '
console.assert isPrime(6479) is false , 'isPrime(6479) is false '
console.assert isPrime(209719) is true , 'isPrime(209719) is true '
console.timeEnd 'test'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment