Reputation: 151
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;
}
Upvotes: 1
Views: 1122
Reputation: 140940
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);
}
Upvotes: 2
Reputation: 90
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;
}
Upvotes: 0