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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With