Fibonacci Sequence
Prints the first terms of the Fibonacci sequence.
- Level
- Beginner
- Topic:
- Math
- Concepts:
- Input & output
- Para
- Math
Open in Codoritmo
Run, change and debug this example in your browser.
What you'll learn
Inside a Para loop, two variables move forward together: each term is the sum of the previous two. At the end, the ratio between terms approaches the golden ratio.
Code
Algoritmo Fibonacci Definir n, i, a, b, siguiente Como Entero Escribir "¿Cuántos términos?" Leer n a <- 0 b <- 1 Escribir Sin Saltar "Primeros ", n, " términos: " Para i <- 1 Hasta n Hacer Escribir Sin Saltar a, " " siguiente <- a + b a <- b b <- siguiente FinPara Escribir "" // a y b son ahora los dos términos que siguen al último mostrado; // su razón se acerca al número de oro (1.618...) Si a > 0 Entonces Escribir "Razón entre los dos términos siguientes: ", b / a FinSiFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
¿Cuántos términos?User answer: 15Primeros 15 términos: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 Razón entre los dos términos siguientes: 1.6180327869
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(n) |
| Average | O(n) |
| Worst | O(n) |
| Memory | O(1) |
Challenge
Print only the even terms.
Show hint
Before writing a, check with a Si whether a MOD 2 = 0.
Related examples
Prime Numbers
Finds every prime number up to a limit.
IntermediateCompound Interest
Watch your savings grow year by year.
IntermediateCaesar Cipher
Encrypts a message by shifting each letter of the alphabet.
Advanced