In your for
loop, you do:
for (int i = 2; i <= 1000000; i++)
{
n = i;
chain = 0;
while (n != 1 && n >= i)
{
chain++;
if ( (n % 2) == 0)
{
n = n / 2;
}
else
{
n = n * 3 + 1;
}
}
//Store the chain length in cache
cache[i] = chain + cache[n];
//-------------------------------
if (cache[i] > chainLength)
{
chainLength = cache[i];
startingNumber = i;
}
}
At some point while (n != 1 && n >= i)
most likely ends up with n
being greater than 1000000
. You'll then access cache
(when you'll do cache[n]
) out of bounds (which are [0:1000000]
).
Add std::cout << "i is " << i << std::endl;
before the while
loop. Add
std::cout << "n is " << n << std::endl;
after. Run the program, you'll get (after some seconds):
...
i is 113381
n is 85036
i is 113382
n is 56691
i is 113383
n is -1812855948
Erreur de segmentation (core dumped)
Here you are. Now, you can use a debugger, identify the bug, fix the bug (most likely rework your loop), and make it work! ;-)
Tip: As n
becomes negative, maybe it reached int
's max value...then simply use a bugger type (like long long int
or uint64_t). Then, you'll most likely not get any overlow (unless you make number
bugger).
C# does not manage memory as C++ does. You may get no error if accessing the array out of bounds here (or, as commented above, you just got lucky). I'm not familiar with C#. Accessing arrays must always be avoided it may have undetermined behaviour (could or could not lead to a crash).