Help with my fibonacci sequence code
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Paul Alequin
el 12 de Sept. de 2018
Comentada: John D'Errico
el 26 de En. de 2023
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... (add previous two numbers together for the next in the sequence)
1. Use a for-end statement to find the 100th number in the sequence.
2. Update this script using a while statement to find the first number in the sequence that has six digits.
============================================================
This is my code until now.
% fibonacci
a=0; b=1; n=input('Enter no, of terms: ');
for i=1:n fprintf('%d',a); fprintf('\t') c=a+b; a=b; b=c;
end
I'm not sure if is correct. But the assignment require to find the 100th number with a for-end and the other part is to find the sequence that has six digits.
2 comentarios
John D'Errico
el 26 de En. de 2023
@Abhishek - actually, it is not correct. It does not solve the assignment. And while it does appear to compute Fibonacci numbers, the code does not do what was required.
Respuesta aceptada
Jim Riggs
el 12 de Sept. de 2018
Editada: Jim Riggs
el 12 de Sept. de 2018
This is how I did it. This function will give the nth number in the Fibonacci sequence:
function f=fib(n)
s=[1, 1];
if n>2
for i=3:n
s(i) = s(i-1)+s(i-2)
end
end
f = s(n)
end
The number of digits in a number, n, is
floor(log10(n))+1
so you can write a loop:
n=1;
nd=1;
while nd < 6
n=n+1
fn = fib(n)
nd = floor(log10(fn))+1;
end
When this loop ends, fn is the first Fibonacci number with 6 digits, and it is the nth in the sequence.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!