forked from gunanksood/C-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci_memoization.c
More file actions
55 lines (39 loc) · 844 Bytes
/
fibonacci_memoization.c
File metadata and controls
55 lines (39 loc) · 844 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* C program for Memoized version for nth Fibonacci number */
#include<stdio.h>
#include<time.h>
#define MAX 100
int lookup[MAX];
/* Function to initialize NIL values in lookup table */
void constructor()
{
int i;
for (i = 0; i < MAX; i++)
{
lookup[i] = -1;
}
}
/* function for nth Fibonacci number */
int fib(int n)
{
if (lookup[n] == -1)
{
if (n <= 1)
lookup[n] = n;
else
lookup[n] = fib(n-1) + fib(n-2);
}
return lookup[n];
}
int main ()
{
int n = 40;
clock_t begin, end;
double time_spent;
constructor();
begin = clock();
printf("Fibonacci number is %d \n", fib(n));
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\nTime Taken %lf", time_spent);
return 0;
}