Fibonacci number without any loops?

10 次查看(过去 30 天)
My problem is to use the fprintf command to print out the first N Fibonacci numbers in a two-column table under heading N and F_N. And for the case N >= 50, print out the last 10 Fibonacci numbers F_i for i = N - 9 in a similar two-column table.

采纳的回答

Roger Stafford
Roger Stafford 2015-2-8
Here is a formula (not using loops) for the Fibonacci numbers ranging from n = n1 to n = n2:
L1 = (1+sqrt(5))/2;
L2 = (1-sqrt(5))/2;
A = 1/sqrt(5);
n = (n1:n2)';
F(n) = round(A*(L1.^n-L2.^n));
(The 'round' call is to correct for round-off errors. The formula is valid up to about n = 70 at which point round-off errors become too large to correct with 'round'.)

更多回答(1 个)

Guillaume
Guillaume 2015-2-8
编辑:Guillaume 2015-2-8
Loren had a blog entry on various methods to calculate Fibonacci numbers. filter is actually very good for this.
Fib = @(n) filter(1, [1 -1 -1], [1 zeros(1, n-1)]);
  1 个评论
John D'Errico
John D'Errico 2015-2-11
I would NOT say it was very good. Filter has good and bad aspects to it for Fibonacci numbers. Filter will probably fail around the same time any other scheme fails in terms of double precision arithmetic.
Filter is nice if you wish to compute all of the Fibonacci numbers that do not exceed a certain limit. As Roger points out, that limit is somewhere around n = 70, although I've not verified his statement.
However, if you just wish to compute certain specific Fibonacci numbers, filter does some extra work, because it computes all of them up to that point. There are other schemes that do not need to compute all such numbers. Roger shows one. I describe in great detail in one of my FEX submissions just some of the many various schemes one might use.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by