Created
September 28, 2015 05:55
-
-
Save kohyama/8e599b2e765ad4256f32 to your computer and use it in GitHub Desktop.
Prime numbers in Clojure
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
(def prime-numbers | |
((fn f [x] | |
(cons x | |
(lazy-seq | |
(f (first | |
(drop-while | |
(fn [n] | |
(some #(zero? (mod n %)) | |
(take-while #(<= (* % %) n) prime-numbers))) | |
(iterate inc (inc x)))))))) | |
2)) |
Thank you.
It's really helping me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanation
in English
prime-numbers
is the sequence gotten by applying2
to the functionf
.The function
f
, when a primex
is given, returns a sequence that iscons
edx
to thelazy-seq
ed sequence which is returned byf
with the prime number next tox
.The prime number next to
x
is thefirst
element of the sequence that elements aredrop
pedwhile
it is a composed number from theiterate
dlyinc
reasing sequence by 1 from the numberinc
reased by 1 fromx
.A number
n
is composed one when it is divided bysome
elements that aretake
nwhile
it's less than or equal to the positive square root ofn
from theprime-numbers
.Though we use
prime-numbers
to askprime-numbers
, things go well because the primes whose square is less than or equal to the candidates of the prime next to it are already gotten.The first prime '2' is all what we should supply.
日本語
素数列
prime-numbers
は, 関数f
の引数に 2 を与えて得られる数列です.関数
f
は, 素数x
を与えると, 次の素数(first ...)
を関数f
に与えて得られる数列を遅延シーケンスにしたもの(lazy-seq ...)
の先頭にx
を付加したシーケンス(cons x ...)
を返します.ある素数
x
の次の素数は,x
の次の数(inc x)
から 1ずつ増加する数列(iterate inc ...)
から, 要素が合成数である間, 要素を捨てたシーケンス(drop-while ...)
の最初の要素です.数
n
が合成数であるかどうか(fn [n] ...)
は, 素数列prime-numbers
のうち,n
の正の平方根以下である間要素を取り出したシーケンス(take-while #(<= (* % %) n) prime-numbers)
の中に,n
を割り切る#(zero? (mod n %))
ものが一つ以上あるか(some ...)
で判定します.素数列
prime-numbers
を求めるのに, 素数列prime-numbers
を使っていますが, 次の素数の候補に対して, 二乗がその数以下であるような素数までは求まっているので, 最初の素数2
だけ用意すれば大丈夫.Example to use
100 primes from 2
primes less than 100
primes greater than or equal to 9,000 and less than 10,000
total sum of primes below 10
total sum of primes below 2,000,000
The answer itself is hidden because it is the answer of https://projecteuler.net/problem=10