3

I have to find all the pythagorean triples which have a value of "c" (where c is the hypotenuse) smaller than an integer number entered by the user. I was able to do this, however I also have to print which triple has the largest value of "c".

# 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);
}
BSMP
  • 4,596
  • 8
  • 33
  • 44
the1whoknocks
  • 89
  • 1
  • 2
  • 6

1 Answers1

2

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 small trick, you can easily speed up your algorithm: any time, you found a^2 + b^2 >= c^2, you can immediately skip the rest for the most inner loop. There are other things you can do to speed up the algorithm further.

Peter Pei Guo
  • 7,770
  • 18
  • 35
  • 54
  • Ok, thanks a lot!! This said, do I use the same principle for the largest "a" and the largest "b"? I would like to print the whole triple that contains the largest c at the end! – the1whoknocks Oct 01 '14 at 02:44