## Posted By

jaircazarin on 10/10/08

## Who likes this?

4 people have marked this snippet as a favorite

# Fibonacci

/ Published in: C

`#include<stdio.h>#define MAX 200/*	F0 = 1.	F1 = 1.	Fn = Fn-1 + Fn-2 */ int fibonacciRecursive(int n){	if(n == 0)		return 0;	if(n == 1)		return 1;	else		return fibonacciRecursive(n-1) + fibonacciRecursive(n-2);} int fibonacciIterative(int n){	int a = 0;	int b = 1;	int fib;	if(n == 0)		return a;	if(n == 1)		return b;	for(int i = 2; i <= n; i++)	{		fib = a + b;		a = b;		b = fib;	}	return fib;} int fibonaccis[MAX];  int fibonacciMemoization(int n){	if(n == 0)		return 0;	if(n == 1)		return 1;	if(fibonaccis[n])		return fibonaccis[n];	else	{		fibonaccis[n] = fibonacciMemoization(n-1)+ fibonacciMemoization(n-2);		return fibonaccis[n];	}} int main(){	for(int i = 0; i < MAX; i++)		fibonaccis[i] = 0;	printf("Fibonacci %d = %d\n", 0, fibonacciMemoization(0));	printf("Fibonacci %d = %d\n", 2, fibonacciMemoization(2));	printf("Fibonacci %d = %d\n", 3, fibonacciMemoization(3));	printf("Fibonacci %d = %d\n", 4, fibonacciMemoization(4));	printf("Fibonacci %d = %d\n", 5, fibonacciMemoization(5));	printf("Fibonacci %d = %d\n", 6, fibonacciMemoization(6));	printf("Fibonacci %d = %d\n", 7, fibonacciMemoization(7));	printf("Fibonacci %d = %d\n", 8, fibonacciMemoization(8));	printf("Fibonacci %d = %d\n", 13, fibonacciMemoization(13));	printf("Fibonacci %d = %d\n", 16, fibonacciMemoization(16));	printf("Fibonacci %d = %d\n", 19, fibonacciMemoization(19));	printf("Fibonacci %d = %d\n", 20, fibonacciMemoization(20));	printf("Fibonacci %d = %d\n", 20, fibonacciMemoization(40));	return 0;} /*	F0 = 0	F2 = 1	F8 = 21	F13 = 233	F16 = 987	F19 = 4181	F20 = 6765*/`