w3resource

Kotlin recursive function: Sum of even Fibonacci numbers

Kotlin Function: Exercise-10 with Solution

From Wikipedia,
In mathematics, the Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones. Numbers that are part of the Fibonacci sequence are known as Fibonacci numbers, commonly denoted Fn . The sequence commonly starts from 0 and 1, although some authors start the sequence from 1 and 1 or sometimes (as did Fibonacci) from 1 and 2. Starting from 0 and 1, the first few values in the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.

Write a Kotlin recursive function to calculate the sum of the even Fibonacci numbers up to a given limit.

Sample Solution:

Kotlin Code:

fun sumEvenFibonacci(limit: Int): Int {
    return sumEvenFibonacciHelper(0, 1, 0, limit)
}

fun sumEvenFibonacciHelper(prev: Int, current: Int, sum: Int, limit: Int): Int {
    if (current > limit) {
        return sum
    }
    
    val newSum = if (current % 2 == 0) sum + current else sum
    
    return sumEvenFibonacciHelper(current, prev + current, newSum, limit)
}

fun main() {
    val limit = 12
    val sum = sumEvenFibonacci(limit)
    println("Sum of even Fibonacci numbers up to $limit: $sum")
}

Sample Output:

Sum of even Fibonacci numbers up to 12: 10

Explanation:

In the above exercise -

The "sumEvenFibonacciHelper()" function takes four parameters: prev and current represent the previous and current Fibonacci numbers, sum represents the sum of the even Fibonacci numbers, and 'limit' specifies the upper limit.

The function follows these steps:

  • If the current Fibonacci number exceeds the 'limit', we have reached the end of the sequence. In this case, the function returns the current sum.
  • If the current Fibonacci number is even, it adds it to the sum using the newSum variable.
  • The function then calls "sumEvenFibonacciHelper()" function with the current Fibonacci number as the new previous. It also uses the sum newSum as the updated sum, and generates the next Fibonacci number by adding the prev and current numbers.
  • The recursive call continues until the current Fibonacci number exceeds the limit, and the final sum is returned.

In the "main()" function, we define a limit variable representing the upper limit of the Fibonacci sequence. We call the sumEvenFibonacci function with this limit and store the result in the sum variable. Finally, we print the sum to the console

Kotlin Editor:


Previous: Sum of digits in a string.
Next: Find maximum depth of binary tree.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.