Implement a function to calculate the nth Fibonacci number iteratively.
HardProblem Statement
Implement a function to calculate the nth Fibonacci number iteratively.
Sample Input
A hardcoded integer, e.g., n = 7.
Sample Output
The 7-th Fibonacci number is: 13
Limits
Time: 2s · Memory: 256 MB
Code Editor
00:00
fun fibonacci(n: Int): Int {
if (n <= 1) return n
var a = 0
var b = 1
for (i in 2..n) {
val temp = b
b += a
a = temp
}
return b
}
fun main() {
val n = 7
println("The $n-th Fibonacci number is: ${fibonacci(n)}")
}
Input
A hardcoded integer, e.g., n = 7.
Expected Output
The 7-th Fibonacci number is: 13