30240184X 数据结构(上) Hailstone(3n+1)问题

这个实例本身没有什么难度,只是马克一下进度。
打算开始学习数据结构 不过囿于数理基础,可能走不了很远。
What so ever,学就vans了,又不是搞什么都需要个意义。

在这里插入图片描述
Hailstone就是我们常说的3n+1问题,偶数减半,奇数3n+1,最后总会回到1(目前还没证明)。

这个小东西可以输出n的Hailstone序列,并统计1到n里每个数的操作次数。
可以看到一会大,一会小,,27的长度甚至比100还要长,捉摸不定。

#include <stdio.h>
void Hailstone(int);
int IJustNeedTheLengthOfHailStoneSequence(int);
int main(int argc, char const *argv[])
{
	int n,i;
	scanf("%d",&n);
	Hailstone(n);
	putchar('\n');
	for(i=1;i<=n;i++)
		printf("%d\n",IJustNeedTheLengthOfHailStoneSequence(i));
	return 0;
}

void Hailstone(int n)
{
	if(n==1) printf("1 ");
	else
	{
		if(n%2==0)
		{
			printf("%d ",n);
			Hailstone(n/2);
		}
		else
		{
			printf("%d ",n);
			Hailstone(3*n+1);
		}
	}
}

int IJustNeedTheLengthOfHailStoneSequence(int n)
{
	int length=1;
	while(n>1)
		{
			n%2==0?(n/=2):(n=3*n+1);
			length++;
		}
	return length;
}

猜你喜欢

转载自blog.csdn.net/weixin_43873801/article/details/85864447
今日推荐