C++original fatorial and optimized factorial method

Original as below via recursion and will call the method itself for many times which is inefficient

int Util::factorial54(int i)
{
    if(i==0 ||i==1)
    {
        return 1;
    }
    else
    {
        return i*factorial54(i-1);
    }
}

 

The Optimized method as below

void Util::factorial55(int *arr, int len, int &result)
{
    arr[0]=1;
    arr[1]=1;
    for(int i=2;i<len;i++)
    {
        arr[i]=i*arr[i-1];
    }
    cout<<"The whole result:"<<endl;
    for(int i=0;i<len;i++)
    {
        cout<<"Index="<<i<<",value="<<arr[i]<<endl;
    }
    result=arr[len-1];
}

void factorial36(int len)
{
    Util ul;
    int *arr=new int[len];
    int result=-1;
    ul.factorial55(arr,len,std::ref(result));
    cout<<"\n\nThe target index="<<len<<",value="<<result<<endl;
}

 

posted @ 2022-03-19 20:38  FredGrit  阅读(18)  评论(0编辑  收藏  举报