Squared triangular number ( Sum of cubes ) | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isTriangular ( int num ) { if ( num < 0 ) return false ; int c = ( -2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return -1 ; float root1 = ( - b + sqrt ( d ) ) / ( 2 * a ) ; float root2 = ( - b - sqrt ( d ) ) / ( 2 * a ) ; if ( root1 > 0 && floor ( root1 ) == root1 ) return root1 ; if ( root2 > 0 && floor ( root2 ) == root2 ) return root2 ; return -1 ; } int isPerfectSquare ( long double x ) { long double sr = sqrt ( x ) ; if ( ( sr - floor ( sr ) ) == 0 ) return floor ( sr ) ; else return -1 ; } int findS ( int s ) { int sr = isPerfectSquare ( s ) ; if ( sr == -1 ) return -1 ; return isTriangular ( sr ) ; } int main ( ) { int s = 9 ; int n = findS ( s ) ; n == -1 ? cout << " - 1" : cout << n ; return 0 ; }