1

Trying to calculate the Fibonacci numbers using a recursive function, but my code is using 2 recursive calls. Is it possible to do it using just one? Would saving the fib number of n-1 into an array or similar and then adding the numbers at end of function, would that work?

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int fib(int n) {
    assert(n >= 0);
    if (n > 1) 
        return fib(n - 1) + fib(n - 2);
    else if (n == 1)
        return 1;
    else 
        return 0;
}

int main(void) {
    int n, f;
    printf("the nth number: ");
    scanf("%d", &n);
    f = fib(n);
    printf("%d \n", f);
    return 0;
}

0

2 Answers 2

2

The following seems to work:

int fib_in(int n, int cur, int prev) {
    if (n == 1 || n == 2) {
        return cur;
    }
    return fib_in(n - 1, cur + prev, cur);
}
int fib(int n) {
    fib_in(n, 1, 1);
}
Sign up to request clarification or add additional context in comments.

Comments

0

The function "fib" must return 2 values.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void fib(int n, int * ra, int * rb) {
    assert(n>=0);
    if (n>1) {
        int ya,yb;
        fib (n-1, &ya, &yb);
        *rb = ya;
        *ra = ya + yb;
    } else if (n==1) {
        *ra = 1;
        *rb = 0;
    } else {
        *ra = 0;
        *rb = 0;
    }
}
int main(int argc, const char * argv[]) {
    int n;
    printf("the nth number: ");
    scanf("%d",&n);
    int ya,yb;
    fib(n, &ya, &yb);
    printf("%d \n", ya);
    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.