Skip to content

Commit ed33d9b

Browse files
authored
Create FibonacciIterative.kt
1 parent 513070d commit ed33d9b

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/kotlin/FibonacciIterative.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Function to calculate Fibonacci numbers iteratively
2+
fun fibonacciIterative(n: Int): Long {
3+
if (n <= 1) {
4+
return n.toLong()
5+
}
6+
7+
var a = 0L
8+
var b = 1L
9+
var result = 0L
10+
11+
for (i in 2..n) {
12+
result = a + b
13+
a = b
14+
b = result
15+
}
16+
17+
return result
18+
}
19+
20+
fun main() {
21+
val index = 15
22+
println("Fibonacci (iterative) of $index is: ${fibonacciIterative(index)}")
23+
}

0 commit comments

Comments
 (0)