idea
The definition of a prime number, I still remember, was taught in elementary school mathematics, "An integer greater than 1, except 1 and itself, cannot be divisible by any other number, it is called a prime number".
To find all prime numbers less than or equal to x, you can use recursive method, let f(x) be all prime numbers less than or equal to x. Then f(2) = [2]
, when x > 2, f(x-1) is all prime numbers less than x. According to the definition of prime numbers, if all the prime numbers in the result of f(x-1) cannot divide x, then x is a prime number, otherwise it is not.
code
Due to the recursive algorithm, the direct implementation may generate a large number of repeated calculations, so we slightly modified it, using a map as a cache, and calculating from small to large, because large numbers will use the results of small numbers.
defmodule Prime do
def primes(x) when x >= 2 do
primes(x, %{2 => [2]}, 3)
end
defp primes(x, m, n) when n > x, do: m[x]
defp primes(x, m, n) do
m = case m[n] do
nil -> Map.put(m ,n, do_primes(m, n))
_ -> m
end
primes(x, m, n+1)
end
defp do_primes(m, n) do
if Enum.all?(m[n-1], fn x -> rem(n, x) != 0 end) do
[n | m[n-1]]
else
m[n-1]
end
end
end
have a test
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。