Count number of triplets ( a , b , c ) such that a ^ 2 + b ^ 2 = c ^ 2 and 1 <= a <= b <= c <= n | Python3 implementation of the approach ; Function to return an ArrayList 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 ; List 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
import math NEW_LINE def getPerfectSquares ( n ) : NEW_LINE INDENT perfectSquares = [ ] NEW_LINE current = 1 NEW_LINE i = 1 NEW_LINE while ( current <= n ) : NEW_LINE INDENT perfectSquares . append ( current ) NEW_LINE i += 1 NEW_LINE current = i ** 2 NEW_LINE DEDENT return perfectSquares NEW_LINE DEDENT def countTriplets ( n ) : NEW_LINE INDENT perfectSquares = getPerfectSquares ( n ** 2 ) NEW_LINE count = 0 NEW_LINE for a in range ( 1 , n + 1 ) : NEW_LINE INDENT aSquare = a ** 2 NEW_LINE for i in range ( len ( perfectSquares ) ) : NEW_LINE INDENT cSquare = perfectSquares [ i ] NEW_LINE bSquare = abs ( cSquare - aSquare ) NEW_LINE b = math . sqrt ( bSquare ) NEW_LINE b = int ( b ) NEW_LINE c = math . sqrt ( cSquare ) NEW_LINE c = int ( c ) NEW_LINE if ( c < a or ( bSquare not in perfectSquares ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( ( b >= a ) and ( b <= c ) and ( aSquare + bSquare == cSquare ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE print ( countTriplets ( n ) ) NEW_LINE DEDENT