We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 9c54dc5 + a372d7d commit 6b14cb4Copy full SHA for 6b14cb4
src/main/kotlin/math/Fibonacci.kt
@@ -0,0 +1,22 @@
1
+/**
2
+ * Returns the n-th Fibonacci number (0-based index) using iteration.
3
+ */
4
+fun fibonacci(n: Int): Long {
5
+ require(n >= 0) { "n must be non-negative" }
6
+ if (n == 0) return 0
7
+ if (n == 1) return 1
8
+ var a = 0L
9
+ var b = 1L
10
+ for (i in 2..n) {
11
+ val temp = a + b
12
+ a = b
13
+ b = temp
14
+ }
15
+ return b
16
+}
17
+
18
+fun main() {
19
+ println("Fibonacci(0) = ${fibonacci(0)}") // 0
20
+ println("Fibonacci(1) = ${fibonacci(1)}") // 1
21
+ println("Fibonacci(10) = ${fibonacci(10)}") // 55
22
0 commit comments