Pythagorean triplets(or triples) consist of three positive integers that satisfy the Pythagorean Theorem,

In this post I will show you how to write a C program that finds the Pythagorean triplets in a given range.

The program asks the user to enter the initial and final points for the range in which the program searches for integers that qualify as Pythagorean Triplets. The program then prints all such triplets found within the given range.

The most basic and naïve approach to do this would be to check whether the different combinations of the numbers within the given range satisfy the Pythagorean condition or not. If they do then just print that combination.

The following program illustrates the process:

### PROGRAM:

/************************************************* ************PYTHAGOREAN TRIPLETS****************** *************************************************/ #include<stdio.h> main(){ int initial,final,a,b,c; printf("Enter the range in which you want to search for Pythagorean Triplets:\nInitial: "); scanf("%d",&initial); printf("\nFinal: "); scanf("%d",&final); printf("The Pythogorean Triplets in the given range are as follows:\n____________________________________________________________\n"); for(a=initial;a<=final;a++){ for(b=a;b<=final;b++){ for(c=b;c<=final;c++){ if(c*c==a*a+b*b){ printf("%d , %d , %d\n",a,b,c); } } } } }

The second, and a better approach would be to generate triplets rather than finding them. To do this we will use the Euclid’s formula(https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple):

### PROGRAM:

/************************************************* ************PYTHAGOREAN TRIPLETS****************** ************************************************** The Following program generates Pythagorean triplets within a given range using Euclid's Formula https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple*/ #include<stdio.h> main(){ int initial,final,a,b,c,m,n; printf("Enter the range in which you want to search for Pythagorean Triplets:\nInitial: "); scanf("%d",&initial); printf("\nFinal: "); scanf("%d",&final); printf("The Pythogorean Triplets in the given range are as follows:\n____________________________________________________________\n"); for(m=initial;m<=final;m++){ for(n=initial;n<=final;n++){ a=m*m-n*n; b=2*m*n; c=m*m+n*n; if(a<=final&&b<=final&&c<=final&&a>=initial&&b>=initial&&c>=initial){ printf("%d , %d , %d\n",a,b,c); } } } }

However, there is one BIG disadvantage to the above approach. It does not generate all the Pythagorean triplets-for example, (9, 12, 15) cannot be generated using integer m and n.

To rectify that, one must insert an additional parameter k to the formula:

where m, n, and k are positive integers with m > n, and with m and n coprime and not both odd.