hubFS: THE place for F#

. . . are you on The Hub?
Welcome to hubFS: THE place for F# Sign in | Join | Help
in Search

Project Euler and EulerPhi

Last post 01-25-2008, 4:41 by CarlMon. 0 replies.
Sort Posts: Previous Next
  •  01-25-2008, 4:41 4656

    Project Euler and EulerPhi

    Hi,

    It took me a while to find a quick algorithm for generating an array of Euler's Totient numbers, so I thought I would share the result.  This is useful for a some Project Euler chalanges.

    #light;;

    ///Returns an array of Euler's Phi numbers starting at Phi(0)
    let EulerPhi n =
      let totarr = Array.init (n + 1) (fun x -> Int64.of_int x)
      {2 .. n} |>
        Seq.iter (fun x ->
       let x64 = Int64.of_int x
          if (totarr.[x] = x64) then
            (totarr.[x] <- totarr.[x] - 1L)
            {(x + x) .. x .. n} |> Seq.iter (fun q -> totarr.[q] <- (totarr.[q] * (x64 - 1L) / x64))
          else ())
      totarr;;

     

    [Edit: Added Int64 casting to prevent integer overflow for large inputs.]

View as RSS news feed in XML
Powered by Community Server, by Telligent Systems