Count all triplets whose sum is equal to a perfect cube | PHP 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
< ? php $ dp = array_fill ( 0 , 1001 , array_fill ( 0 , 15001 , NULL ) ) ; function computeDpArray ( & $ arr , $ n ) { global $ dp ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) { for ( $ j = 1 ; $ j <= 15000 ; ++ $ j ) { if ( $ i == 0 ) $ dp [ $ i ] [ $ j ] = ( $ j == $ arr [ $ i ] ) ; else $ dp [ $ i ] [ $ j ] = $ dp [ $ i - 1 ] [ $ j ] + ( $ arr [ $ i ] == $ j ) ; } } } function countTripletSum ( & $ arr , $ n ) { global $ dp ; computeDpArray ( $ arr , $ n ) ; $ ans = 0 ; for ( $ i = 0 ; $ i < $ n - 2 ; ++ $ i ) { for ( $ j = $ i + 1 ; $ j < $ n - 1 ; ++ $ j ) { for ( $ k = 1 ; $ k <= 24 ; ++ $ k ) { $ cube = $ k * $ k * $ k ; $ rem = $ cube - ( $ arr [ $ i ] + $ arr [ $ j ] ) ; if ( $ rem > 0 ) $ ans += $ dp [ $ n - 1 ] [ $ rem ] - $ dp [ $ j ] [ $ rem ] ; } } } return $ ans ; } $ arr = array ( 2 , 5 , 1 , 20 , 6 ) ; $ n = sizeof ( $ arr ) ; echo countTripletSum ( $ arr , $ n ) ; ? >