2017年1月5日 星期四

Fibonacci with print and value cache

Following is simple way to print Fibonacci(n)

long long fibonacci(int n)
{
    if (n <= 2)
        return 1;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main(...)
{
    int ret = 0;
    int n = 0;

    /* Enter n ... */

    for (; i <= n; i++)
        printf("%lld ", fibonacci(i));

    return 0;
}

However Fibonacci(n) is recalculated in numerous times, we can cache the result for future usage

Following is fibonacci with cache, much faster

long long fibonacci(int n, int *printed, long long *cache)
{
    long long value = 0;

    if (cache[n] != 0)
        value = cache[n];
    else
    {
        if (n <= 2)
            value = 1;
        else
            value = fibonacci(n - 1, printed, cache) +
                           fibonacci(n - 2, printed, cache);

        cache[n] = value;
    }

    if (!printed[n])
    {
        printf("%lld ", value);
        printed[n] = 1;
    }

    return value;
}

int main(...)
{
    int ret = 0;
    int n = 0;
    int *printed = NULL;
    long long *cache = NULL;
    /* Enter n ... */

    /* Allocate memory for printed and cache by n ... */

    fibonacci(n, printed, cache); 

    return 0;  
}