Although this may seem like a duplicate (maybe it is but I haven't found a solution to this version of the problem yet), I don't think it is.
Below is my recursive function which blows python's recursion limit and I'd need to make it iterative instead but I'm having issues seeing how it could be possible.
def countChain(n, cache):
if cache[n] != -1:
return cache[n]
if n % 2 == 0:
cache[n] = 1 + countChain(n / 2, cache)
else:
cache[n] = 2 + countChain((3 * n + 1) / 2, cache)
return cache[n]
Note that here my cache list has 1 million elements in it... (which is why the recursion kills python). I've seen people use an accumulator to do the job but here I'm not returning directly the result of the recursive call which makes this idea hard to implement.
EDIT
the first recursive call should have been cache[n] = 1 + countChain(n / 2, cache) instead of cache[n] = 1 + countChain(n, cache)
EDIT 2
Someone asked for example data so I will simply type in the whole code (not that long) for a better understanding.
import time
import sys
import math
def main():
target = int(sys.argv[1])
start = time.time()
longest = 0
answer = -1
for i in range(int(target/2), target):
if countChain(i) > longest:
longest = countChain(i)
answer = i
print("Result = ", answer, " in ", (time.time() - start), " seconds")
def countChain(n,cache={1:0}):
if n not in cache:
if n % 2 == 0:
cache[n] = 1 + countChain(n//2, cache)
else:
cache[n] = 2 + countChain((3 * n + 1) // 2, cache)
return cache[n]
if __name__ == "__main__":
main()
The usual input is 1000000
Also the else should have been 2 + ...
cache[n] = 1 + countChain(n, cache)are you sure about this? you are invoking the method with the same params again. This seems to me like and endless recursionsys.setrecursionlimit()2 + countChain((3 * n + 1) / 2, cache), and not3+....