系列长度计算

 郭红飞2001 发布于 2023-02-08 17:07

我想计算下面算法给出的系列中的术语数:

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值达到最大递归深度消息时失败.有替代方法吗?

1 个回答
  • 那就是Collat​​z猜想,最后我听说它仍然没有得到证实,它对于所有正整数起点都会收敛到1.除非你能证明收敛,否则很难确定序列长度是多少.

    2023-02-08 17:09 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有