Friday, January 11, 2019

A Pythagorean triplet is a set of three integers a, b and c such that a2 + b2 = c2. Given a limit, generate all Pythagorean Triples with values smaller than given limit.

First Solution
#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);
                }
            }
        }
    }
}
second solution
void pythagoreanTriplets(int limit)
{
  
    // triplet: a^2 + b^2 = c^2
    int a, b, c = 0;
  
    // loop from 2 to max_limitit
    int m = 2;
  
    // Limiting c would limit
    // all a, b and c
    while (c < limit) {
  
        // now loop on j from 1 to i-1
        for (int n = 1; n < m; ++n) {
  
            // Evaluate and print triplets using
            // the relation between a, b and c
            a = m * m - n * n;
            b = 2 * m * n;
            c = m * m + n * n;
  
            if (c > limit)
                break;
  
            printf("%d %d %d\n", a, b, c);
        }
        m++;
    }
}
  
// Driver Code
int main()
{
    int limit = 20;
    pythagoreanTriplets(limit);
    return 0;
}
o/p
3 , 4 , 5
5 , 12 , 13
6 , 8 , 10
8 , 15 , 17
9 , 12 , 15
12 , 16 , 20


No comments:

Post a Comment