3.9 Recursive and non-recursive algorithms of Ackermann function

It is known that the Ackermann function is defined as follows:
Insert picture description here

① Write the recursive algorithm for calculating Ack(m,n), and give the calculation process of Ack(2,1) according to this algorithm.
② Write a non-recursive algorithm for calculating Ack(m,n).

① The recursive algorithm of Ack (m, n) and the calculation process of Ack (2, 1)

/*
  Ack(m,n)的递归算法
*/
int Ack(int m,n){
    
    
	if (m==0) return(n+1);
	else if(m!=0&&n==0) return(Ack(m-1,1));
	else return(Ack(m-1,Ack(m,n-1));
}

/*
  Ack(2,1)的计算过程
*/
Ack(2,1)=Ack(1,Ack(2,0))
		=Ack(1,Ack(1,1))
		=Ack(1,Ack(0,Ack(1,0)))
		=Ack(1,Ack(0,Ack(0,1)))
		=Ack(1,Ack(0,2))
		=Ack(1,3)
		=Ack(0,Ack(1,2))
		=Ack(0,Ack(0,Ack(1,1)))
		=Ack(0,Ack(0,Ack(0,Ack(1,0))))
		=Ack(0,Ack(0,Ack(0,Ack(0,1))))
		=Ack(0,Ack(0,Ack(0,2)))
		=Ack(0,Ack(0,3))
		=Ack(0,4)
		=5

②Ack(m,n) non-recursive algorithm

/*
  Ack(m,n)的非递归算法
*/
int Ack(int m,int n){
    
    
	int a[M][N];
	int i,j;
	for(j=0;j<N;j++){
    
    
		a[0][j]=j+1;
	}
	for(i=1;i<m;i++){
    
    
		for(j=1;j<N;j++){
    
    
			a[i][j]=a[i-1][a[i][j-1]];
		}
	}
	return(a[m][n]);
}

Guess you like

Origin blog.csdn.net/qq_39688282/article/details/108286224