C语言 角谷定理 递归法 初学

情到浓时终转凉″ 提交于 2019-12-20 23:53:08

C语言 角谷定理 递归法 初学

题目:角谷定理。输入一个自然数,若为偶数,则把它除以2,若为奇数,则把它乘以3加1。经过如此有限次运算后,总可以得到自然数值1。求经过多少次可得到自然数1。

代码:

计数并输出每步结果.

#include"stdio.h"
#include"stdlib.h"

int count = 0;

int  jg(int x)
{

	if (x != 1)
	{
		if (x % 2 == 0)
		{
			printf("%d\n", x);
			jg(x/2);
			count++;

		}
		else if (x % 2 != 0)
		{
			printf("%d\n", x);
			jg(3 * x + 1);
			count++;

		}
	}
	if (x == 1)
		printf("%d\n",x);

}

int main()
{

	int x;

	printf("输入一个自然数x:");
	scanf_s("%d", &x);

	jg(x);

	printf("一共经历了%d次运算!\n", count);

	system("pause");
	return 0;
}

正在学习 有什么不妥的 多提意见…

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