欧拉计划的第 14题描述了许多人在这里问过的一个难题。我的问题不是如何解决问题或如何解决其他人的错误。想了想谜底,写了下面的“解法”,但似乎是错误的。有人可以解释我的错误吗?
def main():
# start has all candidate numbers; found has known sequence numbers
start, found = set(range(1, 1000000)), set()
# if are numbers in start, then there are still unfound candidates
while start:
# pick a random starting number to test in the sequence generator
number = start.pop()
# define the set of numbers that the generator created for study
result = set(sequence(number, found))
# remove them from the candidates since another number came first
start -= result
# record that these numbers are part of an already found sequence
found |= result
# whatever number was used last should yield the longest sequence
print(number)
def sequence(n, found):
# generate all numbers in the sequence defined by the problem
while True:
# since the first number begins the sequence, yield it back
yield n
# since 1 is the last sequence number, stop if we yielded it
if n == 1:
break
# generate the next number in the sequence with binary magic
n = 3 * n + 1 if n & 1 else n >> 1
# if the new number was already found, this sequence is done
if n in found:
break
if __name__ == '__main__':
main()
该文档是稍后添加的,希望足够清楚地解释为什么我认为它会起作用。