简体   繁体   中英

Code optimization of recursive function

I am having a recursive function in C as shown below :

float U(int k, int h)
{
    h --;
    int r, s;
    float sum1 = 0, sum2 = 0;

    if (h == -1)
    {
        return (float) ((pow(-1, k)) / factorial(k));
    }

    else
    {
        for (r = 0; r <= k; r++)
        {
            for (s = 0; s <= h; s++)
            {
                sum1 += (r + 1) * (k - r + 1) * U(r + 1, h - s) * U(k - r + 1, s);
            }
        }
        for (r = 0; r <= k; r++)
        {
            for (s = 0; s <= h; s++)
            {
                sum2 += (k - r + 1) * (k - r + 2) * U(r, h - s) * U(k - r + 2, s);
            }
        }
        return (float) ((sum1 + sum2) / (h + 1));
    }
}

I wish to optimize the code as the function takes a lot of time to calculate even not-so-large values like U(10,13) . Please give some suggestions along with code snippets(if possible).

you can memorize the values in an array called arr . use better indentation as your code should be easily understandable. memset the array arr with -1 before running the recursion. the code should look like this -

float arr[100][100];

float U(int k,int h)
{    
    h=h-1;
    int r,s;
    //float sum=0,sum1=0,sum2=0;

    if(h==-1)
    {
        float O_O = (float)(k%2!=0 ? -1:1);
        for(int _w=1; _w<=k; _w++)
            O_O/=(float)_w;
        return O_O;
    }

    if(arr[k][h]<-0.5)return arr[k][h];
    arr[k][h]=0;

    for(r=0;r<=k;r++)
    {
        for(s=0;s<=h;s++)
        {
            arr[k][h]+=(r+1)*(k-r+1)*U(r+1,h-s)*U(k-r+1,s);         
        }       
    }

    for(r=0;r<=k;r++)
    {
        for(s=0;s<=h;s++)
        {
            arr[k][h]+=(k-r+1)*(k-r+2)*U(r,h-s)*U(k-r+2,s);
        }
    }

    return (float)(arr[k][h]/(h+1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM