使用循环和递归的斐波那契数列
我正在 Clojure 中进行 Project Euler 挑战,我想找到斐波那契数列中直到某个数字的所有偶数之和。
执行此操作的函数的代码如下。我知道有更快更简单的方法来做到这一点,我只是尝试使用循环和递归进行递归。然而,代码似乎不起作用,它永远不会返回答案。
(defn fib-even-sum [upto]
(loop [previous 1 nxt 1 sum 0]
(if (or (<= upto 1) (>= nxt upto))
sum)
(if (= (mod nxt 2) 0)
(recur nxt (+ previous nxt) (+ sum nxt))
(recur nxt (+ previous nxt) sum))))
我不确定是否可以在同一个循环中重复两次。我不确定这是否导致了问题?
I am doing the Project Euler challenge in Clojure and I want to find the sum of all the even numbers in a fibonacci sequence up to a certain number.
The code for a function that does this is below. I know there are quicker and easier ways of doing this, I am just experimenting with recursion using loop and recur. However the code doesn't seem to work it never returns an answer.
(defn fib-even-sum [upto]
(loop [previous 1 nxt 1 sum 0]
(if (or (<= upto 1) (>= nxt upto))
sum)
(if (= (mod nxt 2) 0)
(recur nxt (+ previous nxt) (+ sum nxt))
(recur nxt (+ previous nxt) sum))))
I was not sure if I could do recur twice in the same loop or not. I'm not sure if this is causing the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在第一个 IF 中放错了右括号(在
sum
之后)...现在它可以快速工作了
You have a misplaced closing paren in the first IF (after
sum
)...Now it works and fast