Algorithm Analysis
We will compute all Fibonacci numbers in the array fib
, setting fib[i] = F(i)
. Then we will output the required Fibonacci number.
Example
The array fib
will be filled as follows:
Algorithm Implementation
We will compute Fibonacci numbers in the array fib
: fib[i] = F(i)
.
#define MAX 46 int fib[MAX]; // Fill the array according to the recurrence formula. fib[0] = 1; fib[1] = 1; for(int i = 2; i < MAX; i++) fib[i] = fib[i-1] + fib[i-2]; // Read the input value n. Output the answer. scanf("%d",&n); printf("%d\n",fib[n]);
Implementation with Memoization
Declare the array fib
for memorizing Fibonacci numbers: fib[i] = f(i)
.
The recursive function f(n)
finds the -th Fibonacci number.
#define MAX 46 int fib[MAX]; int f(int n) { if (n <= 1) return 1; if (fib[n] != -1) return fib[n]; return fib[n] = f(n-1) + f(n - 2); } // Main part of the program. Read the number n. scanf("%d",&n); // Assign the value -1 to all elements of the array fib. memset(fib,-1,sizeof(fib)); // Find and output the value f(n) printf("%d\n",f(n));