Find value in Fibonacci sequence

2 visualizzazioni (ultimi 30 giorni)
Giuseppe Moio
Giuseppe Moio il 22 Dic 2022
Commentato: Giuseppe Moio il 22 Dic 2022
Hi, i can't solve a problem. Considering the Fibonacci sequence:
function F = Fibonacci(n)
if n == 1
S(1,1) = 0;
elseif n == 2
S(1,1) = 0; S(2,1) = 1;
else
S(1,1) = 0; S(2,1) = 1;
for i = 3:n
S(i,1) = S(i-1,1) + S(i-2,1);
end
end
F = S(n,1);
end
I would like to create a function that accepts two inputs: a natural number m ∈ N and a number j that can take values 0 or 1.
If j = 0, the output is the largest number of the sequence lower than m;
If j = 1, the output is the lowest number of the sequence greater or equal to m.
I can't find a solution. Could someone help me?
Thank you

Risposta accettata

Dyuman Joshi
Dyuman Joshi il 22 Dic 2022
Modificato: Dyuman Joshi il 22 Dic 2022
You don't need to explicitly define condition for n == 1 and n == 2, they can be covered by how you define the sequence.
Now, due to condition on j, while loop would be a better fitting here, as it can cover both conditions.
F=Fib(13,0)
F = 8
F=Fib(13,1)
F = 13
F=Fib(1234567,0)
F = 832040
F=Fib(1234567,1)
F = 1346269
F=Fib(19,4)
Error using solution>Fib
Error, please give a valid value for j
You can do it with a for loop as well, but that wouldn't be recommended for higher values, as the code will be slower because it would be difficult to pre-allocate. However, that will not be the case with this code. Here, the size of array S is same through out all the iterations, just the values are updated.
I've put some temporary error messages, you can change them as per your need.
function F = Fib(m,j)
S=[0 1];
if m~=floor(m)
error('Invalid value for m');
else
while S(end)<m
S = [S(end) sum(S)];
end
if j==0
F=S(1);
elseif j==1
F=S(2);
else
error('Error, please give a valid value for j');
end
end
end

Più risposte (0)

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by