Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1<=a<=b<=c<= n in C++

C++Server Side ProgrammingProgramming

We are given an integer n. The goal is to find triplets ( set of 3 numbers ) that satisfy the conditions −

  • a2+b2=c2

  • 1<=a<=b<=c<=n

We will do this by running two loops for values of 1<=a<=n and 1<=b<=n. Calculate c accordingly (c=sqrt(a2+b2 )) and increment count if both conditions 1 and 2 are met.

Let’s understand with examples.

Input − N=5

Output − Number of triplets − 1

Explanation

for a=3, b=4 and c=5 both conditions are met.

Input − N=3

Output − Number of triplets − 0

Explanation

No such triplets that meet conditions 1 and 2.

Approach used in the below program is as follows

  • Integer N stores the last limit of the range [1,N].

  • Function countTriplets(int n) takes n and returns the count of triplets which satisfy the conditions a2+b2=c2 and 1<=a<=b<=c<=n

  • Variable count stores the number of such triplets, initially 0.

  • Variable sum stores the sum of squares of a and b.

  • Starting from a=1 to n and b=a to n, calculate sum=a*a+b*b and c as square root of sum (sqrt(sum)).

  • If calculated c has value such that c*c==sum and b<=c && c<=n ( both condition 1 and 2 are met ).

  • Increment count as current a,b,c satisfy both conditions.

  • Perform this until a=n and b=n. In the end, count will have a number of such triplets that satisfy the conditions.

  • Return the count as desired result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countTriplets(int n){
   int count = 0;
   int a,b,c;
   a=b=c=1;
   int sum=0;
   for (a = 1; a <= n; a++) //1<=a<=n{
      for (b = a; b <= n; b++) //1<=a<=b<=n{
         sum = a*a + b*b; //a^2 + b^2 =c^2
         c = sqrt(sum);
         if (c * c == sum && b<=c && c<=n) //check 1<=a<=b<=c<=n{
            count++;
            cout<<endl<<"a :"<<a<<" b :"<<b<<" c :"<<c; //to print triplets
         }
      }
   }
   return count;
}
int main(){
   int N = 15;
   cout <<endl<< "Number of triplets : "<<countTriplets(N);
   return 0;
}

Output

If we run the above code it will generate the following output −

Number of triplets :
a :3 b :4 c :5
a :5 b :12 c :13
a :6 b :8 c :10
a :9 b :12 c :154
Number of triplets : 4
raja
Published on 29-Aug-2020 08:54:06
Advertisements