Hailstone

It is an interesting problem in professor Deng’s Mooc.

**Here is the code for Hailstone. **

def hailstone(n):
	length = 1
	while(1 < n):
		if n % 2 == 0:
			n = n/2
		else:
			n = n*3 + 1
		length += 1
	return length

It is quite easy to understand! However,these main features of the algorithm are sometimes not as good to prove as we think.For example,We will think that the finiteness of algorithm is easy to judge,but it is not ture.

Does the above hailstone function satisfy the limit? Means that for any n, while loop will execute a limited number of times and exit?

Regrettably,so far, the academic community cannot prove that for any n, it must be satisfied: hailstone(n) <∞

# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 21:29:36 2020

@author: Gary
"""

import numpy as np
import matplotlib.pyplot as plt

def hailstone(n):
    length=1
    while(1<n):
        if n%2==0:
            n=n//2
        else:
            n=n*3+1
        length+=1
    return length

x=[n for n in range(10000)]
y=[hailstone(h) for h in x]

# 画散点图
plt.scatter(x,y)

#设置横坐标
plt.xticks(np.arange(min(x),max(x)+1),1000)
plt.xlabel('n')
plt.ylabel('hailstone(n)')
plt.show()

在这里插入图片描述
Collatz Conjecture

python code for Collatz Conjecture

def collatz_conjecture(x):
    lists= [x]
    if x<1 :
        return []
    while x > 1:
        if x% 2==0:
            x=x/2
        else:
            x=x*3+1
        lists.append(x)
    return(lists)

collatz_conjecture(6)
collatz_conjecture(93)
collatz_conjecture(180)

猜你喜欢

转载自blog.csdn.net/Garyboyboy/article/details/107325403