zoukankan      html  css  js  c++  java
  • C recursion method as Fibonacci

    struct mapStruct
    {
        int key;
        unsigned long long value;
    };
    
    static struct mapStruct arr[1000];
    
    unsigned long long fab(unsigned long long x);
    void fab13();
    
    int main()
    {
       fab13();
    }
    
    void fab13()
    {
        unsigned long long result=fab(100);
        printf("x=%d,result=%llu\n",10,result);
    }
    
    unsigned long long fab(unsigned long long x)
    {    
        unsigned long long result;
        result=arr[x].value;
        if(result>0)
        {
            return result;
        }
        if(x<=2)
        {
            result=1;
        }
        else
        {
            result= fab(x-1)+fab(x-2);
        }   
        arr[x].key=x;
        arr[x].value=result; 
        return result;
    }

    This has the optimization for original recurison,declare a struct and struct array to store the temp calculated result which will avoid redundant computions.

    struct mapStruct
    {
    int key;
    unsigned long long value;
    };

    static struct mapStruct arr[1000];

    At first it will ask the value from the static arr to detect whether its Fibonacci's value has stored in the struct array.If true,it will return the result directly and no need to run next steps;

    When it can not retrieve value or the Fibonacci's value it will run the conditional way!

  • 相关阅读:
    sql
    java常见异常
    call的用法及NodeList与Array的区别
    os模块
    random模块
    time模块
    序列化模块
    模块介绍
    内置函数
    匿名函数-lambda
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15586676.html
Copyright © 2011-2022 走看看