Count all triplets whose sum is equal to a perfect cube | Python 3 program to calculate all triplets whose sum is perfect cube . ; Function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; Function to calculate triplets whose sum is equal to the perfect cube ; Initialize answer ; count all occurrence of third triplet in range from j + 1 to n ; Driver code
dp = [ [ 0 for i in range ( 15001 ) ] for j in range ( 1001 ) ] NEW_LINE def computeDpArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , 15001 , 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( j == arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + ( arr [ i ] == j ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def countTripletSum ( arr , n ) : NEW_LINE INDENT computeDpArray ( arr , n ) NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , n - 2 , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 , 1 ) : NEW_LINE INDENT for k in range ( 1 , 25 , 1 ) : NEW_LINE INDENT cube = k * k * k NEW_LINE rem = cube - ( arr [ i ] + arr [ j ] ) NEW_LINE if ( rem > 0 ) : NEW_LINE INDENT ans += dp [ n - 1 ] [ rem ] - dp [ j ] [ rem ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 1 , 20 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countTripletSum ( arr , n ) ) NEW_LINE DEDENT