zoukankan      html  css  js  c++  java
  • Python练习题 042:Project Euler 014:最长的考拉兹序列

    本题来自 Project Euler 第14题:https://projecteuler.net/problem=14

    '''
    Project Euler: Problem 14: Longest Collatz sequence
    The following iterative sequence is defined for the set of positive integers:
    
    n → n/2 (n is even)
    n → 3n + 1 (n is odd)
    
    Using the rule above and starting with 13, we generate the following sequence:
    13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
    It can be seen that this sequence (starting at 13 and finishing at 1)
    contains 10 terms. Although it has not been proved yet (Collatz Problem),
    it is thought that all starting numbers finish at 1.
    Which starting number, under one million, produces the longest chain?
    NOTE: Once the chain starts the terms are allowed to go above one million.
    
    Answer: 837799(共有525个步骤)
    '''
    
    import time
    startTime = time.clock()
    
    def f(x):
        c = 0  #计算考拉兹序列的个数
        while x != 1:
            if x%2 == 0:  #若为偶数
                x = x//2
                c += 1
            else:  #若为奇数
                x = x*3+1
                c += 1
        if x == 1:
            c += 1  #数字1也得算上
            return c
    
    chainItemCount = 0
    startingNumber = 0
    for i in range(1, 1000000):
        t = f(i)
        if chainItemCount < t:
            chainItemCount = t
            startingNumber = i
    
    print('The number %s produces the longest chain with %s items' % (startingNumber, chainItemCount))
    
    print('Time used: %.2d' % (time.clock()-startTime))
    

    互动百科说了,考拉兹猜想--又称为3n+1猜想、角谷猜想、哈塞猜想、乌拉姆猜想或叙拉古猜想,是指对于每一个正整数,如果它是奇数,则对它乘3再加1,如果它是偶数,则对它除以2,如此循环,最终都能够得到1。

    判断条件很清楚,所以解题思路也很清晰:把 1-999999 之间的所有数字都拿来判断,计算每个数字分解到1所经历的步骤数,拥有最大步骤数的那个数字(Starting Number)即为解。

    解这题,我的破电脑花了29秒。我隐约感觉这题应该有更好的解法,比如我很不喜欢的递归之类的……

  • 相关阅读:
    WinDbg 查看静态变量
    PLSQL 安装说明
    WinDbg设置托管进程断点
    SQL Server 数据库备份策略,第一周运行失败的原因
    Eclipse开发C/C++ 安装配置图文详解
    C 语言静态链表实现
    C语言结构体,C语言结构体指针,java对象引用,传值,传地址,传引用
    C Primer Plus 收官二叉搜索树实现
    GDB 调试C程序
    C语言 结构体存储空间分配
  • 原文地址:https://www.cnblogs.com/iderek/p/6018933.html
Copyright © 2011-2022 走看看