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 hidden or 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-numbersis the sequence gotten by applying2to the functionf.The function
f, when a primexis given, returns a sequence that isconsedxto thelazy-seqed sequence which is returned byfwith the prime number next tox.The prime number next to
xis thefirstelement of the sequence that elements aredroppedwhileit is a composed number from theiteratedlyincreasing sequence by 1 from the numberincreased by 1 fromx.A number
nis composed one when it is divided bysomeelements that aretakenwhileit's less than or equal to the positive square root ofnfrom theprime-numbers.Though we use
prime-numbersto 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