角谷定理_递归(C语言)

角谷定理。
输入一个自然数,若为偶数,则把它除以 2,若为奇数,则把它乘以 3 加 1。 经过如此有限次运算后,总可以得到自然数值 1。求经过多少次可得到自然数 1。
如:
输入
22
输出
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
STEP=16

#include"stdio.h" 
int count=1;//用于记录 step 
int f(int n) {
 	if(n==1)
	{
	printf("%d ",n);
 	return count;
	}
 	else if(n%2==0) { 
 		printf("%d ",n);
  		f(n/2); 
  		count++; 
  }
   else { 
   		printf("%d ",n); 
  		 f(3*n+1); 
   		count++; 
   }
} 
int main(void) { 
	int n,step; 
	printf("Entern:"); 
	scanf("%d",&n);
	step=f(n); 
	printf("\n"); 
	printf("step= %d \n",step); 
	return 0; 
}

你可能感兴趣的:(角谷定理_递归(C语言))