From d30b486d5c820e47a5f7b29f1eca91ba2979455d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20L=C3=B3pez=20N=C3=BA=C3=B1ez?= Date: Fri, 3 Oct 2025 04:05:14 +0200 Subject: [PATCH] Add iterative Fibonacci function to math directory This PR adds an iterative function to compute the n-th Fibonacci number in Kotlin. The function handles 0-based indices and returns Long to support larger numbers. A main() function is included to test the implementation. --- src/main/kotlin/math/Fibonacci.kt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/main/kotlin/math/Fibonacci.kt diff --git a/src/main/kotlin/math/Fibonacci.kt b/src/main/kotlin/math/Fibonacci.kt new file mode 100644 index 0000000..7fe5937 --- /dev/null +++ b/src/main/kotlin/math/Fibonacci.kt @@ -0,0 +1,22 @@ +/** + * Returns the n-th Fibonacci number (0-based index) using iteration. + */ +fun fibonacci(n: Int): Long { + require(n >= 0) { "n must be non-negative" } + if (n == 0) return 0 + if (n == 1) return 1 + var a = 0L + var b = 1L + for (i in 2..n) { + val temp = a + b + a = b + b = temp + } + return b +} + +fun main() { + println("Fibonacci(0) = ${fibonacci(0)}") // 0 + println("Fibonacci(1) = ${fibonacci(1)}") // 1 + println("Fibonacci(10) = ${fibonacci(10)}") // 55 +}