I am working on a collatz sequence. I currently have a for loop.
for my $num (1..1000000) {
my $count = 1;
for (my $i = $num; $i != 1; $count++) {
$i = $i % 2 ? 3 * $i + 1 : $i / 2;
}
}
And then I have a simple way of working out the count of the loop (who many times it takes to complete the theory).
if ($count > $max_length) {
$max = $num;
$max_length = $count;
}
I worked out that code could be made quicker by using a simple theory.
If n = 3, it would have this sequence {3,10,5,16,8,4,2,1} [8] If n = 6, it would have this sequence {6,3,10,5,16,8,4,2,1} [9] If n = 12, it would have this sequence {12,6,3,10,5,16,8,4,2,1} [10]
So I want to save the result of 3, to be able to work out the result of 6 by just adding 1 to the count and so forth.
I tried to tackle this, with what I thought would do the trick but it infact made my program take 1 minute longer to complete, I now have a program that takes 1.49 seconds rather than 30 seconds I had before.
This is how I added the cache(it's probably wrong)
The below is outside of the for loop
my $cache = 0;
my $lengthcache = 0;
I then have this bit of code which sits after the $i line, line 4 in the for loop
$cache = $i;
$lengthcache = $count;
if ($cache = $num*2) {
$lengthcache++;
}
I don't want the answer given to me in full, I just need to understand how to correctly cache without making the code slower.