【问题标题】:Best Way to Recursively Find Factorials with Memoization in F# [closed]在 F# 中使用记忆递归查找阶乘的最佳方法 [关闭]
【发布时间】:2013-12-12 02:02:37
【问题描述】:

我写了这个笨重的函数,它可以工作但不是最优的。用记忆功能编写递归函数以在 F# 中计算阶乘的好方法是什么?该函数可以将结果返回一个字典类型的数据结构,或者将它们存储在像这个函数一样的变量中。

open System.Collections.Generic

let factorials = Dictionary<int, int>()
factorials.Add(1, 1)

let rec factorial n =
    if n <= 1 then 1
    else
        match factorials.TryGetValue(n) with
        | true, _  -> n * factorial(n-1)
        | false, _ -> 
            factorials.Add(n, n * factorial(n-1))
            n * factorial(n-1)     

let a = factorial 9

【问题讨论】:

  • 这个问题比较适合codereview.stackexchange.com
  • 要考虑的一件事 - 使用 32 位整数不会让您在阶乘方面非常高。最好的解决方案可能就是let res = [1;1;2;6;...]; let fac n = res.[n]。您应该考虑使用大整数以获得更高的精度
  • @ildjarn,John Palmer 已经指出了这一点。我这样做更多的是作为一种学习练习,而不是实际使用代码。我正在尝试使用 F# 解决项目欧拉问题 74,在该问题中,我只需要从 1 到 9 的阶乘。
  • @reggaeguitar - 在这种情况下,使用预先计算的数组几乎肯定是最好的方法。
  • @reggaeguitar :这是一个由近距离投票引起的自动评论,我并不想成为多余的。 ;-]

标签: recursion f# memoization


【解决方案1】:
open System.Collections.Generic

let factorials = Dictionary<int, int>()
factorials.Add(1,1)

let factorial n =
    let dictValue : int ref = ref 0
    let rec factorialWithAcc n limit acc =
        match n with
        | x when n > limit -> ()
        | _ -> 
            let acc = acc * n
            if factorials.TryGetValue(n,dictValue) 
            then ()
            else factorials.Add(n,acc)
            factorialWithAcc (n+1) limit acc
    factorialWithAcc 1 n 1

let printFact () =
    let rec printFact n =
        match n with
        | 0 -> ()
        | _ -> 
            printfn "n: %A, %A" n factorials.[n]
            printFact (n-1)
    printFact factorials.Count

let test () = 
    let result = factorial 9
    printFact ()

test ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 2017-07-07
    • 2018-04-19
    • 2013-07-28
    • 2017-05-10
    • 2020-08-09
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多