Squared triangular number ( Sum of cubes ) | Returns root of n ( n + 1 ) / 2 = num if num is triangular ( or integerroot exists ) . Else returns - 1. ; Considering the equation n * ( n + 1 ) / 2 = num . The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Returns square root of x if it is perfect square . Else returns - 1. ; Find floating point value of square root of x . ; If square root is an integer ; Function to find if the given number is sum of the cubes of first n natural numbers ; Driver code
< ? php function isTriangular ( $ num ) { if ( $ num < 0 ) return false ; $ c = ( -2 * $ num ) ; $ b = 1 ; $ a = 1 ; $ d = ( $ b * $ b ) - ( 4 * $ a * $ c ) ; if ( $ d < 0 ) return -1 ; $ root1 = ( - $ b + sqrt ( $ d ) ) / ( 2 * $ a ) ; $ root2 = ( - $ b - sqrt ( $ d ) ) / ( 2 * $ a ) ; if ( $ root1 > 0 && floor ( $ root1 ) == $ root1 ) return $ root1 ; if ( $ root2 > 0 && floor ( $ root2 ) == $ root2 ) return $ root2 ; return -1 ; } function isPerfectSquare ( $ x ) { $ sr = sqrt ( $ x ) ; if ( ( $ sr - floor ( $ sr ) ) == 0 ) return floor ( $ sr ) ; else return -1 ; } function findS ( $ s ) { $ sr = isPerfectSquare ( $ s ) ; if ( $ sr == -1 ) return -1 ; return isTriangular ( $ sr ) ; } $ s = 9 ; $ n = findS ( $ s ) ; if ( $ n == -1 ) echo " - 1" ; else echo $ n ; ? >