September 5, 2018
Just Juxt #22: Euler's Totient Function (4clojure #75)
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.
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn totient [n]
(let [gcd (fn [a b]
(let [[q r] ((juxt quot rem) b a)]
(if (zero? r) a (recur r a))))]
(if (= n 1) 1
(count (filter #(= 1 (gcd % n)) (range 1 n))))))
(deftest test-75
(is (= (totient 1) 1))
(is (= (totient 10) (count '(1 3 7 9)) 4))
(is (= (totient 40) 16))
(is (= (totient 99) 60)))
(run-tests)