1

I wish to transform the basic Fibonacci function:

int find_fib(int fib_to) {

    if (fib_to == 0) {
        return 0;

    }
    else if (fib_to == 1) {
        return 1;

    }
    else {
        return (find_fib(fib_to - 1) + find_fib(fib_to - 2));       
    }   
}

into one that would use only ONE recursive call. I searched up many sites that tells me to store the value found by (find_fib(fib_to - 1) + find_fib(fib_to - 2)) into some array and then make use of the array, but doing so requires 2 recursive calls.

Any tips on how to solve the problem?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Bee Lau
  • 11
  • 1
  • 2

1 Answers1

2

You mean something like that?

#include <stdio.h>

int fibonacci(int number_iterations, int number_a, int number_b) 
{
    if(number_iterations <= 0) {
        printf("error: 'number_iterations' must be >= 1\n");
        return -1;
    }

    if(number_iterations == 1) {
        printf("%d ", number_a + number_b);
        return number_a + number_b;
    }

    printf("%d ", number_a + number_b);
    return fibonacci(number_iterations - 1, number_b, number_a + number_b);
}

int main()
{
    int a = 1; 
    int b = 1;
    int number_of_iterations = 0;

    printf("Enter a number >= 1: ");

    int err = scanf("%d", &number_of_iterations);
    int final_result = -1;

    if (err != EOF) {
        printf("fibonacci: %d %d ", a, b);
        final_result = fibonacci(number_of_iterations, a, b);
    }

    printf("Final fibonacci: %d\n", final_result);

    return 0;
}

would return you:

Enter a number >= 1: 10
fibonacci: 1 1 2 3 5 8 13 21 34 55 89 144
Final fibonacci: 144
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • Yeah that is similar to what the output result is, but I only need the user to enter the number and then print out the fib of that number (instead of the entire string of fibs). – Bee Lau Mar 10 '15 at 21:56
  • Very simple fix, don't printout anything until after the last index is calculated. Suggest have main() pay attention to the final returned value, as that is what you want to print. – user3629249 Mar 11 '15 at 00:02