Squared triangular number ( Sum of cubes ) | Returns root of n ( n + 1 ) / 2 = num if num is triangular ( or integer root 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
function isTriangular ( num ) { if ( num < 0 ) return 0 ; var c = ( - 2 * num ) ; var b = 1 , a = 1 ; var d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return - 1 ; var root1 = ( - b + Math . sqrt ( d ) ) / ( 2 * a ) ; var root2 = ( - b - Math . sqrt ( d ) ) / ( 2 * a ) ; if ( parseInt ( ( root1 ) ) > 0 && parseInt ( ( Math . floor ( root1 ) ) ) == parseInt ( ( root1 ) ) ) return parseInt ( root1 ) ; if ( parseInt ( ( root2 ) ) > 0 && parseInt ( ( Math . floor ( root2 ) ) ) == parseInt ( ( root2 ) ) ) return parseInt ( ( root2 ) ) ; return - 1 ; } function isPerfectSquare ( x ) { var sr = Math . sqrt ( x ) ; if ( ( sr - Math . floor ( sr ) ) == 0 ) return parseInt ( ( Math . floor ( sr ) ) ) ; else return - 1 ; } function findS ( s ) { var sr = isPerfectSquare ( s ) ; if ( sr == - 1 ) return - 1 ; return isTriangular ( sr ) ; } var s = 9 ; var n = findS ( s ) ; if ( n == - 1 ) document . write ( " " ) ; else document . write ( n ) ;