Python练习题 042:Project Euler 014:最长的考拉兹序列

本文通过编程解决Project Euler第14题:寻找在一百万以下产生最长Collatz序列的起始数字。通过迭代计算从1到999999的所有数字,并找出拥有最长序列的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题来自 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秒。我隐约感觉这题应该有更好的解法,比如我很不喜欢的递归之类的……

转载于:https://www.cnblogs.com/iderek/p/6018933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值