Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | 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
function getPerfectSquares ( n ) { var perfectSquares = [ ] ; var current = 1 , i = 1 ; while ( current <= n ) { perfectSquares . push ( current ) ; current = Math . pow ( ++ i , 2 ) ; } return perfectSquares ; } function countTriplets ( n ) { var perfectSquares = getPerfectSquares ( Math . pow ( n , 2 ) ) ; var count = 0 ; for ( var a = 1 ; a <= n ; a ++ ) { var aSquare = Math . pow ( a , 2 ) ; for ( var i = 0 ; i < perfectSquares . length ; i ++ ) { var cSquare = perfectSquares [ i ] ; var bSquare = Math . abs ( cSquare - aSquare ) ; var b = Math . sqrt ( bSquare ) ; var c = Math . sqrt ( cSquare ) ; if ( c < a || ! perfectSquares . includes ( bSquare ) ) continue ; if ( ( b >= a ) && ( b <= c ) && ( aSquare + bSquare == cSquare ) ) count ++ ; } } return count ; } var n = 10 ; document . write ( countTriplets ( n ) ) ;