Reputation: 159
I'm running this program in C++ to find the sum of all amicable numbers below 10000. Yes, this is my program for Project Euler question 21. I already know that the algorithm is not the most efficient one, and the reason I'm posting this has nothing to do with the efficiency of the program.
Code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int sum = 0;
int d[10000];
for (int i = 0; i <= 9999; i++)
d[i] = 0;
for (int i = 1; i <= 9999; i++)
for (int j = 1; j < i; j++)
if (i%j == 0)
d[i] += j;
for (int i = 1; i <= 9999; i++)
if (d[d[i]] == i)
sum += i;
cout << sum/2;
}
The error seems to occur in the last for
loop - I commented it out and everything runs fine (other than, of course, giving the obviously wrong result of 0). The error message I get is this
followed by this:
----jGRASP exec: C:\Users\Sam\Documents\Project Euler\problem.exe
----jGRASP wedge2: exit code for process is -1073741819.
----jGRASP: operation complete.
And now for the obvious question - WHY is this error happening?
Upvotes: 1
Views: 184
Reputation: 472
If d[i] ever gets a value greater than 10000, then d[d[i]] will be a reference outside the 10000 integers you've allocated. That'll cause an error.
Upvotes: 0
Reputation: 206607
This line
if ( d[d[i]] == i)
is going access d
beyond the valid range of indices since d[i]
can be greater than 9999
.
Change it to:
if ( d[i] <= 9999 && d[d[i]] == i)
Upvotes: 2