Finding n-th fibonacci numbers larger than 100

5 views (last 30 days)
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
James Tursa on 11 Mar 2019
Post the code you have so far and we can make comments and suggestions for moving forward.
Anastasijasup
Anastasijasup on 11 Mar 2019
%
%
function f=fibonacciNumbers(n)
if(n<=1)
f=n;
else f=fibonacciNumbers(n-1)+fibonacciNumbers(n-2)
end
end
%then i started a new script with while cycle and got stuck:
while (f>=100)
for k=1:n
f=fibonacciNumbers(n);
end
end

Sign in to comment.

Answers (1)

Guillaume
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
Anastasijasup
Anastasijasup on 11 Mar 2019
Thank you for a great explanation! I did a little search and this is how i changed my loop:
still not sure if it is written correctly
f=0;
k=0;
while (f>=100)
k=k+1;
f=fibonacciNumbers(k);
end
fibonacciNumbers(4)
fibonacciNumbers(6)
fibonacciNumbers(10)
Guillaume
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

Sign in to comment.

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!