61 lines
1.7 KiB
C
61 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/03/30 00:36:22 by tosuman ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#define NUM_TYPE int
|
|
|
|
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;
|
|
NUM_TYPE fibn;
|
|
|
|
if (index < 0)
|
|
return (-1);
|
|
cache = malloc(sizeof(NUM_TYPE) * (index + 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;
|
|
free(cache);
|
|
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);
|
|
}
|
|
*/ ////
|