Created
August 4, 2013 20:40
-
-
Save joshuawscott/6151859 to your computer and use it in GitHub Desktop.
Prime numbers
Simple recursion to find primality up to 40,000
This file contains 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
defmodule Prime do | |
def known_primes, do: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199] | |
def is_prime(n) when n > 9409, do: :cannot_calculate | |
def is_prime(n) when n < 2, do: false | |
def is_prime(2), do: true | |
def is_prime(n), do: check_primes(n, known_primes) | |
def check_primes(_,[]), do: true | |
def check_primes(n, [head|_tail]) when head*head > n, do: true | |
def check_primes(n, [head|tail]), do: rem(n, head) != 0 and check_primes(n, tail) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment