piscine-c05/ex04/ft_fibonacci.c

60 lines
1.7 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_fibonacci.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tosuman </var/spool/mail/tosuman> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/30 00:36:21 by tosuman #+# #+# */
/* Updated: 2023/04/01 02:20:35 by tischmid ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#define NUM_TYPE int
#define MAX_INDEX 10000
NUM_TYPE memoized_fibonacci(unsigned int index, NUM_TYPE *cache)
{
if (cache[index] == (NUM_TYPE) -1)
cache[index] = memoized_fibonacci(index - 1, cache)
+ memoized_fibonacci(index - 2, cache);
return (cache[index]);
}
int ft_fibonacci(int index)
{
int i;
NUM_TYPE cache[MAX_INDEX + 1];
NUM_TYPE fibn;
if (index < 0)
return (-1);
cache[0] = 0;
cache[1] = 1;
i = 2;
while (i < index + 1)
cache[i++] = (NUM_TYPE)(-1);
fibn = memoized_fibonacci((unsigned int) index, cache);
i = 0;
return (fibn);
}
/* ////
#include <stdio.h>
#define UNSIGNED_LONG_LONG_MAX_FIB 93
#define INT_MAX_FIB 46
int main(void)
{
int i;
i = -12;
while (++i <= INT_MAX_FIB + 1)
printf("%d-th fib num: %d\n", i, ft_fibonacci(i));
return (0);
}
*/ ////