Ackerman函数的非递归表示

/************************************************************************/
/* 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);
}

 

转载于:https://www.cnblogs.com/lisongfeng9213/p/3383250.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值