How to print the Pythagorean triplet with the largest hypotenuse

I need to find all Pythagorean triples that have a "c" value (where c is a hypotenuse) less than a user-entered integer. I was able to do this, however I also need to print which triplet has the highest "c" value.

# include <stdio.h>

int main()
{
    int i=1, N, a, b, c;

    printf("Please enter an integer number: ");
    scanf("%d", &N);

    for(c=1; c<N; c++)
    {
        for(b=1; b<c; b++)
        {
            for(a=1; a<b; a++)
            {
                if((a*a)+(b*b)==(c*c))
                {
                    printf("\n%d.(%d,%d,%d)\n", i++, a, b, c);
                }
            }
        }
    }

    printf("\nThere are %d triples which contain a c<N.\n\n", (i++)-1);

    system("PAUSE");
    return(0);
}

      

+3


source to share


1 answer


You can have a variable to remember the largest c. Below commented lines are added, take a look:

int largest_c = 0; //define it
for(c=1; c<N; c++)
{
    for(b=1; b<c; b++)
    {
        for(a=1; a<b; a++)
        {
            if((a*a)+(b*b)==(c*c))
            {
                if (c > largest_c) { //found a bigger one, so remember it
                     largest_c = c;
                }
                printf("\n%d.(%d,%d,%d)\n", i++, a, b, c);
            }
        }
    }
}

      



By the way, with a little trick, you can easily speed up your algorithm: anytime you find a ^ 2 + b ^ 2> = c ^ 2, you can skip the rest of it right away for the innermost loop. There is more that can be done to speed up the algorithm.

+2


source







All Articles