Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | C ++ implementation of the approach ; Function to return an Array containing all the perfect squares upto n ; While current perfect square is less than or equal to n ; Function to return the count of triplet ( a , b , c ) pairs such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n ; Vector of perfect squares upto n ^ 2 ; Since , a ^ 2 + b ^ 2 = c ^ 2 ; If c < a or bSquare is not a perfect square ; If triplet pair ( a , b , c ) satisfy the given condition ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > getPerfectSquares ( int n ) { vector < int > perfectSquares ; int current = 1 , i = 1 ; while ( current <= n ) { perfectSquares . push_back ( current ) ; current = pow ( ++ i , 2 ) ; } return perfectSquares ; } int countTriplets ( int n ) { vector < int > perfectSquares = getPerfectSquares ( pow ( n , 2 ) ) ; int count = 0 ; for ( int a = 1 ; a <= n ; a ++ ) { int aSquare = pow ( a , 2 ) ; for ( int i = 0 ; i < perfectSquares . size ( ) ; i ++ ) { int cSquare = perfectSquares [ i ] ; int bSquare = abs ( cSquare - aSquare ) ; int b = sqrt ( bSquare ) ; int c = sqrt ( cSquare ) ; if ( c < a || ( find ( perfectSquares . begin ( ) , perfectSquares . end ( ) , bSquare ) == perfectSquares . end ( ) ) ) continue ; if ( ( b >= a ) && ( b <= c ) && ( aSquare + bSquare == cSquare ) ) count ++ ; } } return count ; } int main ( ) { int n = 10 ; cout << countTriplets ( n ) ; return 0 ; }