当i是正整数时,有一个函数f(i)满足以下条件。
f(0) = 0,
f(1) = 1
f(i) = f(i-1) + f(i-2)
所以,基于以上所述,我想写一个程序来确定f(i)。 并编写一个程序来确定f(1000)。
答案 0 :(得分:2)
由于您似乎打开了编程语言,我选择了python,这对于这些事情很有用。
您可以这样做:
def f(i):
if i == 0:
return 0
elif i == 1:
return 1
return f(i-1)+f(i-2)
如果您想更加高效,请使用迭代器:
def f():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
代码运行速度非常快:
for i, val in enumerate(f()):
if i == 1000:
print val
break
并返回您想要的值f(1000),即:
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
@DmitryBychenko:你返回的值实际上是f(999)。
@MartinEvans:你的代码实际上是不正确的(关闭1)。一个显而易见的方法是f(1)和f(2)返回的值是错误的:
>>> def f(i):
... a,b = 0, 1
... for i in range(i-1):
... a,b = b, a+b
... return a
...
>>> f(0)
0
>>> f(1)
0
>>> f(2)
1
>>> f(3)
1
答案 1 :(得分:1)
第100个Fibonacci数是巨大值,因此需要BigInteger
(C#)或其类似物。 C#实现可以是这样的(我怀疑它是否会被接受作为家庭作业代码)。
private static IEnumerable<BigInteger> fibo() {
yield return 0;
yield return 1;
BigInteger first = 0;
BigInteger second = 1;
while (true) {
BigInteger result = first + second;
first = second;
second = result;
yield return result;
}
}
// Skip(1000) since it's defined that f(0) == 0 - unusual sequence starting;
// in mathematics sequences usually started from the 1st item
Console.Write(fibo().Skip(1000).FirstOrDefault().ToString());
答案是
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
答案 2 :(得分:1)
以下Python 3.0脚本将起作用:
def f(i):
a, b = 0, 1
for i in range(i):
a, b = b, a + b
return a
print(f(0))
print(f(1))
print(f(2))
print(f(3))
print(f(1000))
给你:
0
1
1
2
和
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
答案 3 :(得分:0)
显然,这需要bc:
#!/usr/bin/bc --quiet
define fib(n) {
auto a,b,i;
if(n<2)return n;a=0;b=1;for(i=1;i<n;++i){c=a+b;a=b;b=c}return b;}
print fib(1000), "\n"
quit