-1

I wrote some code in python and C to find solutions for z^2 = x^2 + y^2, x, y and z being all integers. From the python code, which seems to work fine, I know how many solutions there are for some given range. For x and y ranging from 1 to 10000, there should be 14471 unique solutions, or double that, 28942 counting duplicates.

In the following code if I use the ranges from 1 to 1000 for x and y, and set the array solutions to have an appropriate size(2064 in this case) the code works fine. But when I try extend the range of x and y to 1 to 10000, I get a segfault, but don't know why so.

int main()
{
  int solutions[28942][2]={0};
  int counter = 0;

  for(int x=1;x<10000;++x)
  {
    for(int y=1; y<10000;++y)
    {
      float z = sqrt(x*x + y*y);
      if(z == (int) z) 
      {
        solutions[counter][0] = x;
        solutions[counter][1] = y;
        ++counter;
      }
    }
  }

  for(int i = 0;i<28942;++i)
  {
    printf("This is a solution: {%d,%d}\n",solutions[i][0],
                                           solutions[i][1]);
  }

  printf("value of counter is %d\n",counter );
}
TomBombadil
  • 83
  • 1
  • 7

3 Answers3

4

Maybe your code accepts solutions that are not legit. Comparing floats to int is a tricky business.

try doing it like this:

int z = (int) sqrt(x*x + y*y);

if(z*z == (x*x + y*y)) {
    solutions[counter][0] = x;
    solutions[counter][1] = y;
    ++counter;
}

that way you're comparing integers only

Tawcharowsky
  • 615
  • 4
  • 18
2
  • Avoid declaring large arrays on the stack, as it may cause stack overflows. A stack overflow might manifest itself as a seg fault. solutions should be declared dynamically with malloc() instead.
  • Never do floating point comparisons using the == operator. This is because of the inaccurate nature of floating points and nothing unique to C. See this. Instead you need to check

    if ( abs(z - (int)z) >= EPSILON)
    

    where EPSILON is some appropriate constant, for example 0.0001f.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
1

Most likely, your stack is not big enough to hold nearly 60000 ints.

Try to allocate it as a global variable (in the data segment), or use dynamic memory allocation.

user1635881
  • 239
  • 3
  • 11