Kotlin Program to Print Fibonacci Series
var a = 0; var b = 1; for (i in 1..n) { print("$a "); val sum = a + b; a = b; b = sum; } where n is the number of terms.Examples
How to Think About It
Algorithm
Code
fun main() {
val n = 10
var a = 0
var b = 1
for (i in 1..n) {
print("$a ")
val sum = a + b
a = b
b = sum
}
}Dry Run
Let's trace printing 5 Fibonacci numbers through the code
Initialize
a = 0, b = 1, n = 5
Iteration 1
Print a=0; sum=0+1=1; a=1; b=1
Iteration 2
Print a=1; sum=1+1=2; a=1; b=2
Iteration 3
Print a=1; sum=1+2=3; a=2; b=3
Iteration 4
Print a=2; sum=2+3=5; a=3; b=5
Iteration 5
Print a=3; sum=3+5=8; a=5; b=8
| Iteration | a (printed) | sum | a (updated) | b (updated) |
|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 1 |
| 2 | 1 | 2 | 1 | 2 |
| 3 | 1 | 3 | 2 | 3 |
| 4 | 2 | 5 | 3 | 5 |
| 5 | 3 | 8 | 5 | 8 |
Why This Works
Step 1: Start with first two numbers
We begin with a = 0 and b = 1 because the Fibonacci series starts with 0 and 1.
Step 2: Print current number
In each loop, we print the current number a which represents the current Fibonacci term.
Step 3: Calculate next number
We find the next Fibonacci number by adding a + b, then update a and b to move forward in the series.
Alternative Approaches
fun fibonacci(n: Int): Int {
return if (n <= 1) n else fibonacci(n - 1) + fibonacci(n - 2)
}
fun main() {
val n = 10
for (i in 0 until n) {
print("${fibonacci(i)} ")
}
}fun fibonacciSequence(n: Int) = sequence {
var a = 0
var b = 1
repeat(n) {
yield(a)
val sum = a + b
a = b
b = sum
}
}
fun main() {
fibonacciSequence(10).forEach { print("$it ") }
}Complexity: O(n) time, O(1) space
Time Complexity
The loop runs n times, each time doing constant work, so time is O(n).
Space Complexity
Only a few variables are used regardless of n, so space is O(1).
Which Approach is Fastest?
The iterative loop is fastest and most memory efficient compared to recursion which has exponential time and sequence which uses lazy evaluation but more overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loop | O(n) | O(1) | Simple and fast for all n |
| Recursive | O(2^n) | O(n) | Small n, easy to understand |
| Sequence generator | O(n) | O(1) | Kotlin idiomatic, lazy evaluation |