Problem 14關於Project Euler描述了許多人在此詢問的某個難題。我的問題不是如何解決問題或如何解決其他人的錯誤。在思考這個難題之後,寫了下面的「解決方案」,但似乎是錯誤的。有人能解釋我的錯誤嗎?一個錯誤的答案顯然意味着一個邏輯錯誤,但什麼是錯誤的思想?
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()
該文檔稍後添加,希望能夠足夠清楚地解釋爲什麼我認爲它會起作用。
爲什麼不使用遞歸和記憶化? –
這個「解決方案」使用一個記憶形式與'start'和'found'集合一起使用。 –
我喜歡你的問題標題! –