Ackerman函数的非递归表示

断了今生、忘了曾经 提交于 2019-11-27 00:31:58

/************************************************************************/
/* akm={ n+1             m=0                                            */
/*       akm(m-1,1)      m!=0,n=0                                       */
/*       akm(m-1,akm(m,n-1))  m!=0,n1=0                                */
/* Ackerman函数                                                         */
/* nflag其实可以不用存在,本意想让其标志是否向下传递top的f给top-1的n,其实每一步都需要传递,所以不需要存在*/
/************************************************************************/
#include <stdio.h>
const int MaxSize=100;
struct
{
    int f;
    int m;
    int n;
    int flag;//1表示函数值没有计算出来
    int nflag;//1标志n是需要重新计算(是否需要向下求值)
}st[MaxSize];
int top=-1;
int ackerman(int m,int n)
{
    top++;
    st[top].m=m;
    st[top].n=n;
    st[top].flag=1;
    st[top].nflag=0;
    while(top>-1)
    {
        if (st[top].flag==1)
        {
            if (st[top].m==0)
            {
                st[top].f=st[top].n+1;
                st[top].flag=0;
            }
            else if (st[top].m!=0&&st[top].n==0)
            {
                st[top].flag=1;
                st[top].m=st[top].m-1;
                st[top].n=1;
                st[top].nflag=0;
            }
            else if (st[top].m!=0&&st[top].n!=0)
            {
                st[top].flag=1;
                st[top].m=st[top].m-1;
                st[top].nflag=1;
                top++;
                st[top].m=st[top-1].m+1;
                st[top].n=st[top-1].n-1;
                st[top].flag=1;
                st[top].nflag=1;
            }
        }
        else if (st[top].flag==0&&top!=0)
        {
            st[top-1].n=st[top].f;
            top--;
        }
        else if (st[top].flag==0&&top==0)
        {
            printf("%d\n",st[top].f);
            return 0;
        }

    }
}
int main()
{
    ackerman(3,2);
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!