Question

x^2 + y^2 = Z^2. How to test the truth of Pythagoras Theorem in code? My assignment says to read in 10 integers and test if the statement is true or false with each of the ten integers. This is what I have but I'm not sure if its right because I'm not sure if I'm solving for z.

Any help appreciated

void ESearch(int array[], int size)
{
int trueCount = 0;
//int falseCount = 0;

for(int i = 0; i < size; ++i)
{
    for(int j = 0; j < size; ++j)
    {

        int x = array[i];
        int y = array[j];

        int z = sqrt(pow(x, 2)+ pow(y, 2));

        if(z == x || y)
        {
            ++trueCount;
        }

    }


}
if(trueCount > 0) cout << "\nE is TRUE"; else cout << "\nE is FALSE";

 }
Was it helpful?

Solution

Your code won't work the way you want. Try this. You have very small data size, so most probably you don't care much about efficiency, but I wrote some simple (not yet the most efficient) solution using STL. You define a vector and sort it once in order then to use binary search when you want to check whether the pair (x,y) satisfies Pyth. theorem for some other integer from your input data. It takes log(size), so it should be reasonably fast even for large data inputs. Also you don't need to run second loop from the beginning of the data, since you'll be already checking the same pair but in different order before. The code should fairly simple, but if you have any questions, please ask. Good luck.

void ESearch(int array[], int size)
{

int trueCount = 0;
std::vector<int> z(array, array + size);
std::sort(z.begin(), z.end());

int x, y;
double z_check;

for(int i = 0; i < size; i++)
{
    x = array[i];

    for(int j = i+1; j < size; j++)
    {
        y = array[j];

        z_check = sqrt(x*x + y*y);

        if(std::binary_search(z.begin(), z.end(), z_check))
        {
            trueCount++;
        }

    }
}
z.clear();
if(trueCount > 0) cout << trueCount; else cout << "\nE is FALSE";
}

EDIT: You can even speed up things a bit more since you know that you are looking for the number greater than sqrt(x*x+y*y) in sorted vector:

if(std::binary_search(z.begin() + ceil(z_check), z.end(), z_check))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top