我想计算下面算法给出的系列中的术语数:
if n=1 STOP: if n is odd then n=3n+1 else n=n/2
例如,如果n为22,则系列将如下所示,系列的长度将为16:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
我在python中想出了下面的递归函数:
class CycleSizeCalculator(object): ''' Class to calculate the cycle count of a number. Contains the following members: counter - holds the cycle count number - input number value calculate_cycle_size() - calculates the cycle count of the number given get_cycle_length() - returns the cycle count ''' def calculate_cycle_size(self,number): """ Calculates the cycle count for a number passed """ self.counter+=1# count increments for each recursion if number!=1: if number%2==0: self.calculate_cycle_size((number/2)) else: self.calculate_cycle_size((3*number)+1) def __init__(self,number): ''' variable initialization ''' self.counter = 0 self.number = number self.calculate_cycle_size(number) def get_cycle_length(self): """ Returns the current counter value """ return self.counter if __name__=='__main__': c = CycleSizeCalculator(22); print c.get_cycle_length()
这在大多数情况下都有效,但是在某些n值达到最大递归深度消息时失败.有替代方法吗?
那就是Collatz猜想,最后我听说它仍然没有得到证实,它对于所有正整数起点都会收敛到1.除非你能证明收敛,否则很难确定序列长度是多少.