Creating Brute Force Way

In this method, we will using nested loops and check every elements in an array.

static bool isTriplet(int[] ar, int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            for (int k = j + 1; k < n; k++)
            {

            }
        }
    }
    // If we reach here, no triplet found
    return false;
}

We will calculate square each element and check if the triplets can fit in pythagoras equation.

for (int i = 0; i < n; i++)
{
    for (int j = i + 1; j < n; j++)
    {
        for (int k = j + 1; k < n; k++)
        {
            // Calculate square of array elements
            int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];

            if (x == y + z || y == x + z || z == x + y)
                return true;
        }
    }
}

results matching ""

    No results matching ""