Hey People! This program gives you all Pythagorean triplets in a given range.( Eg. ( 3,4,5) - 3^2+4^2 = 5^2 ). I've used a pointer to allocate memory to hold the squares of all numbers in the range. The program uses a function to search for element in the array.

67 Views
``````#include <stdio.h>
#include <conio.h>
#include <math.h>

int SQR( int num ){ return num*num; }
int Found( int , int*, int );

int main()
{
int upperlim,lowerlim,range,i,j,sum,count=0;
int *squares;

printf("Enter lower limit:");scanf("%d",&lowerlim );
printf("Enter upper limit:");scanf("%d",&upperlim );
range = upperlim - lowerlim +1;
if( range < 1 )
{
printf("Range too low");
goto exit;
}

squares = (int*) malloc( sizeof(int)*range);

if( ! squares )
{
exit("Not enough memory!");
goto exit;
}

for( i=0; i<=range-1; i++ )
{
squares[i] = SQR(lowerlim+i);
}

for( i=lowerlim; i<=upperlim; i++ )
{
for( j=lowerlim; j<=upperlim; j++ )
{
sum = SQR(i) + SQR(j);
if( Found( sum, squares, range ))
{
printf("\n(%d %d %0.0f)",i,j,sqrt(sum));
count++;
}
}
}
printf("\n%d triplets found",count );
exit:
getch();
return 0;
}

int Found( int num, int* a, int range )	// Carry out linear search
{										// for a given number in array
int i;
for( i=0; i<=range-1; i++ )
{
if( a[i] == num )
return 1;
}

return 0;
}``````