其中两种方法
1、迭代法(循环)
#include <stdio.h>
int main()
{
int n = 0;
int count = 0;//步数
scanf("%d", &n);//输入
while (1 != n)//数据处理
{
if (0 == n % 2)//为偶数时
{
n /= 2;
}
else//为奇数时
{
n = n * 3 + 1;
}
count++;//每循环一次步数加一
}
printf("%d\n", count);//输出
return 0;
}
2、递归法
#include <stdio.h>
int count_step(int n)
{
if (1 != n)
{
if (0 == n % 2)//为偶数的情况
{
return 1 + count_step(n / 2);
}
else//为奇数的情况
{
return 1 + count_step(n * 3 + 1);
}
}
return 0;
}
int main()
{
int n = 0;
scanf("%d", &n);//输入
printf("%d\n", count_step(n));//数据处理并输出
return 0;
}

京公网安备 11010502036488号