D
D
Denis Akhunov2021-03-03 20:43:02
Kotlin
Denis Akhunov, 2021-03-03 20:43:02

Can you suggest how to translate the program into recursion?

Hello, I've tried a lot, but I still can't figure out how to convert such a program to recursion?
Of course, it would be easier to write just for (i in 0 until 7), something like that, but the console program must be universal for any entered values, as it turned out to be done in the 1st program
Condition:
Write a recursive function for calculating numbers Fibonacci: 1,1,2,3,5,8,13,21,…
Using it, find the first seven odd terms of the sequence.
source:

fun fibonacci(n: Int) {
    var fibonacci1 = 0
    var fibonacci2 = 1
    var fibonacci: Int
    if ( n == 1 ) print("1 ")
    if ( n > 1 )
    {
        var k = 0
        print( "1 ")
        while(k != n-1 )
        {
            fibonacci = fibonacci1 + fibonacci2
            if ( fibonacci % 2 != 0 ) {
                k++
                print ("$fibonacci ")
            }
            fibonacci1 = fibonacci2
            fibonacci2 = fibonacci
        }
    }
}
fun main()
{
    //Написать рекурсивную функцию вычисления чисел Фибоначчи: 1,1,2,3,5,8,13,21,… Используя ее, найти…
    //первые семь нечетных членов последовательности.
    print("Введите кол-во чисел Фибоначчи, которые хотите увидеть: ")
    val n = readLine()!!.toInt()
    fibonacci(n)
}


code that is available for recursion:
fun fibonacci(n: Int): Int {
        if(n == 0) return 0;
        if(n == 1 || n == 2) return 1;

        return fibonacci(n-1)+fibonacci(n-2);
}
fun output(n: Int) {
    var k = 0
    var value = n
    for (i in 0 until value)
    {
        while (k != n)
            if (fibonacci(i) % 2 != 0) {
                print("${fibonacci(i)} ")
                k++
            }
        value++
    }
}
fun main()
{
    //Написать рекурсивную функцию вычисления чисел Фибоначчи: 1,1,2,3,5,8,13,21,… Используя ее, найти…
    //первые семь нечетных членов последовательности.
    print("Введите кол-во чисел Фибоначчи, которые хотите увидеть: ")
    val n = readLine()!!.toInt()
    output(n)
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2021-03-03
@zagayevskiy

Since we are talking about Kotlin, we definitely need a version with tail recursion.

fun fib(n: Int) = recursiveFib(n, 1, 1)
private tailrec fun recursiveFib(n: Int, p1: Int, p2: Int): Int = when (n) {
   1 -> p1
   2 -> p2
   else -> recursiveFib (n - 1, p2, p1+p2)
}

V
Vasily Bannikov, 2021-03-03
@vabka

In general, calculating fibonacci numbers through recursion is much easier than iteratively)
Defining fibonacci numbers
F(1) = 1
F(2) = 1
F(x) = F(x - 1) + F(x - 2)

fun fib(n: Int): Int = when (n) {
    1,2 -> 1
    else -> fib(n-1) + fib(n-2)
}

(only there is no error handling here)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question