Search code examples
c++nested-loops

Difference in two for nested loops.(C++)


I tried to solve the following problem:

Let x,y,z be integers in the domain [-5,5]. Display the number of solutions (x,y,z) that satisfy 3*x+y^3-z^2=0. My initial solution was this:

int main() {
    int x=-6;
    int y=-6;
    int z=-6;
    int p=0;
    for(int i=-5; i<6; i++)
    {
        x++;
        for (int j=-5; j<6; j++)
        {
            y++;
            for(int k=-5; k<6; k++)
            {
                z++;
                if(3*x +y*y*y -z*z==0)
                    p++;          
            }
        }
    }
    std::cout<< p ;
    return 0;
}

This is the correct solution:

 int main() {
        int x=-5;
        int y=-5;
        int z=-5;
        int p=0;
        for( x=-5; x<=5; x++)
           for (y=-5; y<=5; y++)
               for( z=-5; z<=5; z++)
                   if(3*x +y*y*y -z*z==0)
                       p++;

        std::cout<< p;
        return 0;
}

Why are these two different and what did I do wrong in the first one?


Solution

  • In the incorrect code, the variables y and z are not reset to the beginning of their range at the begining of the loop.

    An even shorter correct exemple would be:

    int main()
    {
        int p = 0;
        for( int x=-5; x<=5; ++x )
           for( int y=-5; y<=5; ++y )
               for( z=-5; z<=5; ++z)
                   if( 3*x + y*y*y - z*z == 0 )
                       ++p;
        std::cout << p << std::endl;
        return 0;
    }
    

    The variable initializations can be put directly into the loops. As they are trivial variables there is no performance penalty.