Created
October 24, 2014 06:20
-
-
Save adacola/55f73d416abd6ef83864 to your computer and use it in GitHub Desktop.
Euler's totient function in F#
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
let totient n = | |
let rec totient isFirst (r, n) d = | |
match n % d with | |
| 0 -> totient false (r * (d - (if isFirst then 1 else 0)), n / d) d | |
| _ -> r, n | |
let nearlyPrimes = seq { yield 2; for i in 3 .. 2 .. n do yield i } | |
((1, n), nearlyPrimes) ||> Seq.fold (totient true) |> fst | |
let totientTest() = | |
let expected = [1; 1; 2; 2; 4; 2; 6; 4; 6; 4] | |
let actual = [for i in 1 .. 10 -> totient i] | |
if actual <> expected then failwith "expected : %A, but : %A" expected actual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References : http://sucrose.hatenablog.com/entry/2014/04/22/005557