希望用不同语言不同算法实现下面的递归操作
本帖最后由 badyun 于 2020-10-28 22:52 编辑希望以各种方式和语言实现下面的递归操作,纯属技术讨论,回帖100%奖励
https://vip.d0.badyun.com/img/c3aee3533fb25c9d148e4830c440753fb9c61f71d5bef275327659e2c26b880d.png
我先抛砖引玉,写一段js的实现
function calc(n) {
const fib = (n, sum1 = 1, sum2 = 1) => {
if (n <= 2) return sum2;
return fib(n - 1, sum2, sum1 + sum2)
}
if (n == 1) return 1
else if (n % 2 == 0) return fib(n / 2 + 1)
return 2 * fib((n + 1) / 2)
}
效果如下
https://vip.d0.badyun.com/img/f760dc30c2d542dd5369fb0caa09223e4aced5845e0fbf0ee5b5b4959c5f3b01.png
#include <stdio.h>
unsigned int fib(unsigned int n, unsigned int sum1 = 1, unsigned int sum2 = 1) {
if (n <= 2) return sum2;
return fib(n - 1, sum2, sum1 + sum2);
}
unsigned int calc(unsigned int n) {
if (n == 1) return 1;
else if (n % 2 == 0) return fib(n / 2 + 1);
return 2 * fib((n + 1) / 2);
}
int main() {
for (unsigned int i = 1; i < 10; i++) {
printf("%u: %u\n", i, calc(i));
}
return 0;
}
1: 1
2: 1
3: 2
4: 2
5: 4
6: 3
7: 6
8: 5
9: 10 本帖最后由 no-problem 于 2020-10-29 00:40 编辑
突然感觉好难
牛逼牛逼
这版主睡着了吧 这个好难啊 貌似楼主的错了 2L是正确的 def fib(n, sum1=1, sum2=1):
return fib(n-1, sum2, sum1+sum2) if n > 2 else sum2
def calc(n):
return 1 if n == 1 else 2*fib((n+1)/2) if n % 2 else fib(n/2+1)
for i in range(8):
print(f'第{i}年, {calc(i)}') var fib = (n, sum1 = 1, sum2 = 1) => n > 2 ? fib(n - 1, sum2, sum1 + sum2) : sum2;
var calc = n => n === 1 ? 1 : n % 2 ? 2 * fib((n + 1) / 2) : fib(n / 2 + 1)
for (var i = 0; i <= 7; i++) {
console.log(`第${i}年,${calc(i)}`)
} 有空研究一下。。。。 孤阳不生 孤阴不长