Squared triangular number ( Sum of cubes ) | Java program to check if a given number is sum of cubes of natural numbers . import java . Math . * ; ; Returns root of n ( n + 1 ) / 2 = num if num is triangular ( orinteger 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
class GFG { public static int isTriangular ( int num ) { if ( num < 0 ) return 0 ; int c = ( - 2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return - 1 ; double root1 = ( - b + Math . sqrt ( d ) ) / ( 2 * a ) ; double root2 = ( - b - Math . sqrt ( d ) ) / ( 2 * a ) ; if ( ( int ) ( root1 ) > 0 && ( int ) ( Math . floor ( root1 ) ) == ( int ) ( root1 ) ) return ( int ) ( root1 ) ; if ( ( int ) ( root2 ) > 0 && ( int ) ( Math . floor ( root2 ) ) == ( int ) ( root2 ) ) return ( int ) ( root2 ) ; return - 1 ; } static int isPerfectSquare ( double x ) { double sr = Math . sqrt ( x ) ; if ( ( sr - Math . floor ( sr ) ) == 0 ) return ( int ) ( Math . floor ( sr ) ) ; else return - 1 ; } static int findS ( int s ) { int sr = isPerfectSquare ( s ) ; if ( sr == - 1 ) return - 1 ; return isTriangular ( sr ) ; } public static void main ( String [ ] args ) { int s = 9 ; int n = findS ( s ) ; if ( n == - 1 ) System . out . println ( " - 1" ) ; else System . out . println ( n ) ; } }