本文介绍了在Clojure中创建tribonacci数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人能够帮助我创建一个函数,将给出一个数字将返回对应于该数字的tribonacci数字例如
10将返回44
15将返回927

I was wondering if someone would be able to help me create a function that would given a number would return the tribonacci number that corresponds to that number for example10 would return 4415 would return 927

推荐答案

通常,您应该显示您已经尝试过的内容,然后告诉我们您遇到了什么问题,你修复。请求堆栈溢出从头开始为你做这个是不礼貌。

Generally, you should show what you have already tried and then let us know what problem you are having, so we can point you to a fix. Asking Stack Overflow to do this for you from scratch is poor manners.

但是,我喜欢Clojure和这些问题是有趣的。首先,有这么多方法可以做到这一点,只是谷歌Clojure斐波那契将让你开始在许多不同的方向为此。

But, I love Clojure and these problems are fun. First of all, there are so many ways to do this, and just googling Clojure fibonacci will get you started in many many different directions for this.

这里是一个快速示例使用 reduce

Here is a quick example using reduce:

(defn tri [x]
   (last (reduce
            (fn [[a b c] n]
               (conj [b c] (+ a b c))) [0 0 1] (range (- x 3)))))

您还可以使用 iterate

(nth(iterate(fn [[abc]] [bc(+ abc)])[0 0 1])5)

这会从第一组tribonacci数字返回第5个,其中 [0 0 1] 是初始集。

This returns the 5th from the first set of tribonacci numbers, where [0 0 1] is the initial set.

要从第X个索引获得确切的结果,还可以将其包装在如上所示的函数中:

To get an exact result from X'th index, also wrap it in a function as above, like so:

(defn tri-iterate [x]
   (last
     (nth (iterate (fn [[a b c]] [b c (+ a b c)]) [0 0 1]) (- x 3))))

方法。

这篇关于在Clojure中创建tribonacci数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:23