Finding n-th fibonacci numbers larger than 100
5 views (last 30 days)
Show older comments
hello, I have a task to find 4th,6th and 10th fibonacci number,larger ️than 100. I think i should use while function, but i am pretty neew to matlab and not sure how the code should look like. in addition, the n and f(n) must be shown too. maybe u could give me a hint how i should do it or just help with the task please
4 Comments
James Tursa
on 11 Mar 2019
Post the code you have so far and we can make comments and suggestions for moving forward.
Answers (1)
Guillaume
on 11 Mar 2019
I would suggest you do some research into fibonacci algorithms as the one you've implemented is the most inefficient one. It will be very slow even for moderately large n.
It gets even worse with your loop. If it were correctly written, it would calculate fib(1) on the first step, fib(2) which recalculate fib(1) again on the 2nd step, fib(3) which recalculate fib(2), then fib(1) (twice!) on the 3rd step. etc. So for fib(n) you're recalculating all the previous that you'd already calculated multiple times.
At the moment, you work from n and work back to 1. You would be better off calculating fib(1) check that if it's greater than your threshold, then calculate fib(2) (which is trivially calculated if you already know fib(2), again check against your threshold, etc. Each time you add a new term instead of recursing.
WIth regards to your loop, you need to choose between for and while. Inventing a syntax that mixes the two together is certainly not going to work.
Example implementation with a while:
n = 0;
while condition_not_met
n = n + 1;
something = function_of_n(n);
end
The same with for:
for n = 1 : some_arbitrary_upper_bound %could be Inf
something = function_of_n(n);
if condition_met
break; %quit loop
end
end
2 Comments
Guillaume
on 11 Mar 2019
Unlike C and related languages you don't need () brackets around a condition in matlab.
As I wrote, with a while it's
while condition_NOT_MET
%...
end
not
while condition_MET
%...
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!