[4Clojure]解题记录-#75

Euler's Totient Function
 

 

Difficulty: Medium
Topics:

Two numbers are coprime if their greatest common divisor equals 1. Euler's totient function f(x) is defined as the number of positive integers less than x which are coprime to x. The special case f(1) equals 1. Write a function which calculates Euler's totient function.

 
(= (__ 1) 1)
 
(= (__ 10) (count '(1 3 7 9)) 4)
 
(= (__ 40) 16)
 
(= (__ 99) 60)
 
解长度100:
#(count 
   (for [i (range %)  
        :let [j (+ 1 i) 
               g ((fn f [x y](let [r (mod x y) q (quot x y)](if (= 0 r) y (f y r)))) j %)]      :when (= g 1)] j))
中间过程:
先写最大公约数,gcd,是递归的
(defn gcd [x y](let [r (mod x y) q (quot x y)](if (= 0 r) y (gcd y r))))
user=> (gcd 3 6);3 
user=> (gcd 4 6);2 
for从1到n,把里面和n互质的找出来(= 1 (gcd i n))
最后count个数,把gcd变成匿名函数,以及最外层的匿名函数用写成语法糖形式。
posted @ 2014-11-27 19:21  TomAndRainy  阅读(208)  评论(0编辑  收藏  举报