Skip to content

Instantly share code, notes, and snippets.

@adacola
Created October 24, 2014 06:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adacola/55f73d416abd6ef83864 to your computer and use it in GitHub Desktop.
Save adacola/55f73d416abd6ef83864 to your computer and use it in GitHub Desktop.
Euler's totient function in F#
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
@adacola
Copy link
Author

adacola commented Oct 24, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment