Showing posts with label Program to print pythagorean triplets upto certain number. Show all posts
Showing posts with label Program to print pythagorean triplets upto certain number. Show all posts

Monday, December 30, 2013

Pythagorean Triplets

A Pythagorean Triplet is set of three positive integers (a,b,c) such that



a2+b2=c2

For example (3,4,5) , (5,12,13), etc.

Multiplying the triplets with a same number gives another triplets
for example 2*(3,4,5)=(6,8,10)

Following is the program to print Pythagorean Triplets where (a,b,c)<100 and can not be multiple of each other or factorised by each other i.e. if there is a set of (3,4,5) then (6,8,10) shoulnd be part of output.

#include<stdio.h>
#include<math.h>
int check(int x,int y,int z)
{
        int i=2,r1,r2,r3,r;
        while(i<=x)
               {
                   r1=x%i;
                   r2=y%i;
                   r3=z%i;
                   r=r1+r2+r3;

                   if(r==0)
                      break;
                   else
                       i++;
                }

           if (r==0)
                return 0;
           else
                return 1;
}



int main()
{

       float t=0;
       int a=0, u=0;
       int i, j;


       for(i=3;i<100;i++)
               {
                      for(j=i+1;j<100;j++)
                            {
                                 u=i*i+j*j;
                                 /*
                                  sqrt() belongs to math.h header file. sqrt(4)=2, sqrt(4.5)=2.12132
                                 */
                                  t=sqrt(u);
                                  a=t;
                                   /* 
                                   ceil() belongs to math.h header file. ceil(4.6)=5
                                   floor() belongs to math.h header file. floor(4.6)=4
                                  */
                                   if(ceil(t)==floor(t)&& check(i,j,a))
                                              printf("(%d,%d,%d)\n",i,j,a);
                             }
                   }
           return 0;
}