Can someone explain the Fibonacci sequence in kotlin? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone explain the Fibonacci sequence in kotlin?

fun main(args: Array<String>) { println("Enter a number n>1 : ") var num = readLine()!!.toInt() var result = mutableListOf(0,1) //0,1,1,2,3,5 " for (i in 2..num-1){ result.add(result[i-2] + result[i-1]) } " println(result) } The code in the double quotes is creating a confusion. I cannot understand why i-2 and i-1 is taken

17th Feb 2023, 11:31 AM
<k>Kartik</k>
1 Answer
+ 6
The code you have in quotes is a for loop that is used to calculate the Fibonacci sequence. The reason it uses i-2 and i-1 is because the Fibonacci sequence is defined as the sum of the two previous numbers. That is, the nth number in the Fibonacci sequence is the sum of the (n-1)th and (n-2)th numbers. Let's break down the loop step by step: for (i in 2..num-1) { result.add(result[i-2] + result[i-1]) } 1. The loop starts at index 2 and goes up to num-1. This is because we already have the first two numbers of the Fibonacci sequence (0 and 1) in the result list. 2. Inside the loop, we use the add method of the MutableList class to add a new number to the result list. 3. The new number is the sum of the two previous numbers in the sequence, which are located at indices (i-2) and (i-1) in the result list. 4. The loop continues to add new numbers to the result list until it reaches the (num-1)th index, at which point it stops.
17th Feb 2023, 11:41 AM
VSYZ
VSYZ - avatar