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 wit
As has been said, the simplest way is to get some memoization to avoid recomputing things that haven't been computed. You might be interested in knowing that there is no cycle if you being from a number under one million (no cycle has been discovered yet, and people have explored much bigger numbers).
To translate it in code, you can think the python way:
MEMOIZER = dict()
def memo(x, func):
global MEMOIZER
if x in MEMOIZER: return MEMOIZER[x]
r = func(x)
MEMOIZER[x] = r
return r
Memoization is a very generic scheme.
For the Collatze conjecture, you might run in a bit of a pinch because numbers can really grow and therefore you might blow up the available memory.
This is traditionally handled using caching, you only cache the last n
results (tailored to occupy a given amount of memory) and when you already have n
items cached and wish to add a newer one, you discard the older one.
For this conjecture there might be another strategy available, though a bit harder to implement. The basic idea is that you have only ways to reach a given number x
:
2*x
(x-1)/3
Therefore if you cache the results of 2*x
and (x-1)/3
there is no point in caching x
any longer >> it'll never get called anymore (except if you wish to print the sequence at the end... but it's only once). I leave it to you to take advantage of this so that your cache does not grow too much :)