Squared triangular number ( Sum of cubes ) | Python3 program to check if a given number is sum of cubes of natural numbers . ; 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
import math NEW_LINE def isTriangular ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT c = ( - 2 * num ) ; NEW_LINE b = 1 ; NEW_LINE a = 1 ; NEW_LINE d = ( b * b ) - ( 4 * a * c ) ; NEW_LINE if ( d < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT root1 = ( - b + math . sqrt ( d ) ) // ( 2 * a ) ; NEW_LINE root2 = ( - b - math . sqrt ( d ) ) // ( 2 * a ) ; NEW_LINE if ( root1 > 0 and math . floor ( root1 ) == root1 ) : NEW_LINE INDENT return root1 ; NEW_LINE DEDENT if ( root2 > 0 and math . floor ( root2 ) == root2 ) : NEW_LINE INDENT return root2 ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) ; NEW_LINE if ( ( sr - math . floor ( sr ) ) == 0 ) : NEW_LINE INDENT return math . floor ( sr ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT def findS ( s ) : NEW_LINE INDENT sr = isPerfectSquare ( s ) ; NEW_LINE if ( sr == - 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return int ( isTriangular ( sr ) ) ; NEW_LINE DEDENT s = 9 ; NEW_LINE n = findS ( s ) ; NEW_LINE if ( n == - 1 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) ; NEW_LINE DEDENT