Problem 25 : 1000-digit Fibonacci number
The Fibonacci sequence is defined by the recurrence relation:
= + , where = 1 and = 1.
Hence the first 12 terms will be:
= 1
= 1
= 2
= 3
= 5
= 8
= 13
= 21
= 34
= 55
= 89
= 144
The 12th term, , is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
思路 :
斐波那契数列的题我们在之前的欧拉计划好像遇到过了,所以一看到这个题目,心里边美滋滋,因为斐波那契数列的思想我早已心知肚明了,这个成语放在这用好像有点不太合适,但暂且先这样吧!马上敲下matlab的代码!
clear,clc
tic
j = 3;
a = 1;
b = 1;
c = 0;
while c < 10^2
c = b + a;
if c < 10^2
a = b;
b = c;
j = j + 1;
else
break
end
end
disp(j);
toc
运行结果1477,很开心,转到欧拉计划的页面填入答案,说时迟,那时快!一个辣眼睛的红叉叉出现,我不信,再试了一遍,结果我就不说了。为什么呢?回到matlab的界面,调开变量框,发现位数超过308位,matlab就会显示Inf.
那可怎么办呢?查资料ing.............,终于在这找到了灵感,见下图
不好意思,拿错了,不过这正好也是自然中的斐波那契数列,就不修改了,见下图
nice,还有这种操作,每个斐波那契数都可以用图中从上往下第二个公式表示,再推导一下!
两边取对数
其中
把它写成关于n的表达式就行了。
其实也可以计算器算!
代码 :
clear,clc
tic
n = ceil((1000-1 + log10(5)/2)/log10((1+sqrt(5))/2));
toc
disp(n)
结果 :4782