Hailstone Sequence

Hailstone Sequence

Hailstone Sequence现如今不能够证明其正确性。
输入任何一个大于1的正整数N,如果是偶数的话就除以2,如果是奇数的话就乘以3再加上1,最后这个数都会变为1。特殊地,当输入为1时,序列为1。其公式如下:

img

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cstring>
using namespace std;
int main(int argc,char* argv[])
{
int* hailstone = new int[500];
int i;
cin>>hailstone[0];
for(i=1;i<500;i++){
int pre = hailstone[i-1];
if(pre==1)
break;//特殊情况
else if(pre%2==0)//偶数时
hailstone[i]=pre/2;
else
hailstone[i]=pre*3+1;//基数时
}
cout<<"hailstone("<<hailstone[0]<<")={";
for(int j=0;j<i;j++)
cout<<hailstone[j]<<" ";
cout<<"}"<<"\n";
cout<<"数列长度:"<<i<<endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
def hailstoneSequence(n):
print(n, end = ' ')
if n == 1:
return 1
elif (n % 2) == 0:
n //= 2
hailstoneSequence(n)
else:
n = n * 3 + 1
hailstoneSequence(n)

num = int(input(">"))
print("The Hailstone Sequence is: ")
hailstoneSequence(num)

参考资料

Hailstone Sequence 冰雹序列