作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 Haskell 比较陌生。问题是找到不大于 400 万的所有偶数斐波那契数的总和。我不能使用列表。
如果我理解正确,下面的解决方案是错误的,因为它使用了列表:
my_sum = sum $ filter (odd) $ takeWhile (< 4000000) fibs
findsum threshold = findsum' 0 1 0 threshold
findsum' n1 n2 accu t
| n2 > t = accu
| odd n2 = findsum' n2 n3 accu t
| otherwise = findsum' n2 n3 accu2 t
where
n3 = n2 + n1
accu2 = accu + n2
最佳答案
您可能会发现在 excel 中构建它然后从那里找出代码更容易。在excel中很容易做到这一点。只需将 1 放在第一个单元格中,然后将 1 放在它的正下方。然后将下面的每个单元格添加到它上面的两个单元格。 (即,单元格 a3 包含 =A1+A2)。使下一列仅包含偶数值“即,if(mod(a3,2)==0,a3,0)”。接下来,将您的运行总和放在第三列中。基于此,您应该能够提出递归解决方案。
另一种方法是从问题开始。你只想要一个为累加器尖叫的总数。
sumFib :: Integer -> Integer
sumFib threshold = sumFib' 1 1 0 threshold
sumFib' :: Integer -> Integer -> Integer -> Integer -> Integer
sumFib' n1 n2 acc threshold
sumFib :: Integer -> Integer
sumFib threshold = sumFib' 1 1 0 threshold
sumFib' :: Integer -> Integer -> Integer -> Integer -> Integer
sumFib' n1 n2 acc threshold
| n1 > threshold = acc
| otherwise = sumFib' (n2+n1) n1 newAcc threshold
where newAcc = if n1 `mod` 2 == 0
then n1 + acc
else acc
关于haskell - 斐波那契数的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2776685/
我是一名优秀的程序员,十分优秀!