Squared triangular number (Sum of cubes)
Last Updated :
11 Jul, 2025
Given a number s (1 <= s <= 1000000000). If s is sum of the cubes of the first n natural numbers then print n, otherwise print -1.
First few Squared triangular number are 1, 9, 36, 100, 225, 441, 784, 1296, 2025, 3025, ...
Examples :
Input : 9
Output : 2
Explanation : The given number is
sum of cubes of first 2 natural
numbers. 1*1*1 + 2*2*2 = 9
Input : 13
Output : -1
A simple solution is to one by one add cubes of natural numbers. If current sum becomes same as given number, then we return count of natural numbers added so far. Else we return -1.
C++
// C++ program to check if a
// given number is sum of
// cubes of natural numbers.
#include <iostream>
using namespace std;
// Function to find if
// the given number is
// sum of the cubes of
// first n natural numbers
int findS(int s)
{
int sum = 0;
// Start adding cubes of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Driver code
int main()
{
int s = 9;
int n = findS(s);
n == -1 ? cout << "-1" : cout << n;
return 0;
}
C
// C program to check if a
// given number is sum of
// cubes of natural numbers.
#include <stdio.h>
// Function to find if
// the given number is
// sum of the cubes of
// first n natural numbers
int findS(int s)
{
int sum = 0;
// Start adding cubes of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Driver code
int main()
{
int s = 9;
int n = findS(s);
n == -1 ? printf("-1") : printf("%d",n);
return 0;
}
// This code is contributed by kothavvsaakash.
Java
// Java program to check if
// a given number is sum of
// cubes of natural numbers.
class GFG
{
// Function to find if
// the given number is
// sum of the cubes of
// first n natural numbers
static int findS(int s)
{
int sum = 0;
// Start adding cubes of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Drivers code
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);
}
}
Python3
# Python3 program to find
# if the given number is
# sum of the cubes of first
# n natural numbers
# Function to find if the
# given number is sum of
# the cubes of first n
# natural numbers
def findS (s):
_sum = 0
n = 1
# Start adding cubes of
# the numbers from 1
while(_sum < s):
_sum += n * n * n
n += 1
n-= 1
# If sum becomes equal to s
# return n
if _sum == s:
return n
return -1
# Driver code
s = 9
n = findS (s)
if n == -1:
print("-1")
else:
print(n)
C#
// C# program to check if a
// given number is sum of
// cubes of natural numbers.
using System;
class GFG
{
// Function to find if the
// given number is sum of
// the cubes of first n
// natural numbers
public static int findS(int s)
{
int sum = 0;
// Start adding cubes of
// the numbers from 1
for (int n = 1; sum < s; n++)
{
sum += n * n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Driver code
static public void Main (string []args)
{
int s = 9;
int n = findS(s);
if (n == -1)
Console.WriteLine("-1");
else
Console.WriteLine(n);
}
}
// This code is contributed by Ajit.
PHP
<?php
// PHP program to check if
// a given number is sum of
// cubes of natural numbers.
// Function to find if the
// given number is sum of
// the cubes of first n
// natural numbers
function findS($s)
{
$sum = 0;
// Start adding cubes of
// the numbers from 1
for ($n = 1; $sum < $s; $n++)
{
$sum += $n * $n * $n;
// If sum becomes equal to s
// return n
if ($sum == $s)
return $n;
}
return -1;
}
// Driver code
$s = 9;
$n = findS($s);
if($n == -1)
echo("-1");
else
echo($n);
// This code is contributed by Ajit.
?>
JavaScript
<script>
// Javascript program to check if a
// given number is sum of
// cubes of natural numbers.
// Function to find if
// the given number is
// sum of the cubes of
// first n natural numbers
function findS(s)
{
let sum = 0;
// Start adding cubes of
// the numbers from 1
for (let n = 1; sum < s; n++)
{
sum += n * n * n;
// If sum becomes equal to s
// return n
if (sum == s)
return n;
}
return -1;
}
// Driver code
let s = 9;
let n = findS(s);
n == -1 ? document.write("-1") :document.write(n);
// This code is contributed by aashish1995
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
An efficient solution is based on the formula [n(n+1)/2]2 for sum of first n cubes. We can see that all numbers are squares.
1) Check if given number is perfect square.
2) Check if square root is triangular (Please see method 2 of triangular numbers for this)
C++
// C++ program to check if a
// given number is sum of
// cubes of natural numbers.
#include <bits/stdc++.h>
using namespace std;
// Returns root of n(n+1)/2 = num
// if num is triangular (or integer
// root exists). Else returns -1.
int isTriangular(int num)
{
if (num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) - (4 * a * c);
if (d < 0)
return -1;
// Find roots of equation
float root1 = ( -b + sqrt(d)) / (2 * a);
float root2 = ( -b - sqrt(d)) / (2 * a);
// checking if root1 is natural
if (root1 > 0 && floor(root1) == root1)
return root1;
// checking if root2 is natural
if (root2 > 0 && floor(root2) == root2)
return root2;
return -1;
}
// Returns square root of x if it is
// perfect square. Else returns -1.
int isPerfectSquare(long double x)
{
// Find floating point value of
// square root of x.
long double sr = sqrt(x);
// If square root is an integer
if ((sr - floor(sr)) == 0)
return floor(sr);
else
return -1;
}
// Function to find if the given number
// is sum of the cubes of first n
// natural numbers
int findS(int s)
{
int sr = isPerfectSquare(s);
if (sr == -1)
return -1;
return isTriangular(sr);
}
// Driver code
int main()
{
int s = 9;
int n = findS(s);
n == -1 ? cout << "-1" : cout << n;
return 0;
}
C
// C program to check if a
// given number is sum of
// cubes of natural numbers.
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
// Returns root of n(n+1)/2 = num
// if num is triangular (or integer
// root exists). Else returns -1.
int isTriangular(int num)
{
if (num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) - (4 * a * c);
if (d < 0)
return -1;
// Find roots of equation
float root1 = ( -b + sqrt(d)) / (2 * a);
float root2 = ( -b - sqrt(d)) / (2 * a);
// checking if root1 is natural
if (root1 > 0 && floor(root1) == root1)
return root1;
// checking if root2 is natural
if (root2 > 0 && floor(root2) == root2)
return root2;
return -1;
}
// Returns square root of x if it is
// perfect square. Else returns -1.
int isPerfectSquare(long double x)
{
// Find floating point value of
// square root of x.
long double sr = sqrt(x);
// If square root is an integer
if ((sr - floor(sr)) == 0)
return floor(sr);
else
return -1;
}
// Function to find if the given number
// is sum of the cubes of first n
// natural numbers
int findS(int s)
{
int sr = isPerfectSquare(s);
if (sr == -1)
return -1;
return isTriangular(sr);
}
// Driver code
int main()
{
int s = 9;
int n = findS(s);
n == -1 ? printf("-1") : printf("%d",n);
return 0;
}
// This code is contributed by kothavvsaakash.
Java
// Java program to check
// if a given number is
// sum of cubes of natural
// numbers.
// import java.Math.*;
class GFG
{
// Returns root of n(n+1)/2 = num
// if num is triangular (or
// integer root exists). Else
// returns -1.
public static int isTriangular(int num)
{
if (num < 0)
return 0;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) -
(4 * a * c);
if (d < 0)
return -1;
// Find roots of equation
double root1 = (-b +
Math.sqrt(d)) / (2 * a);
double root2 = (-b -
Math.sqrt(d)) / (2 * a);
// checking if root1 is natural
if ((int)(root1) > 0 &&
(int)(Math.floor(root1)) ==
(int)(root1))
return (int)(root1);
// checking if
// root2 is natural
if ((int)(root2) > 0 &&
(int)(Math.floor(root2)) ==
(int)(root2))
return (int)(root2);
return -1;
}
// Returns square root
// of x if it is perfect
// square. Else returns -1.
static int isPerfectSquare(double x)
{
// Find floating point
// value of square root of x.
double sr = Math.sqrt(x);
// If square root
// is an integer
if ((sr - Math.floor(sr)) == 0)
return (int)(Math.floor(sr));
else
return -1;
}
// Function to find if the
// given number is sum of
// the cubes of first n
// natural numbers
static int findS(int s)
{
int sr = isPerfectSquare(s);
if (sr == -1)
return -1;
return isTriangular(sr);
}
// Driver code
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);
}
}
// This code is contributed
// by mits.
Python3
# Python3 program to check
# if a given number is sum of
# cubes of natural numbers.
import math
# Returns root of n(n+1)/2 = num
# if num is triangular (or integer
# root exists). Else returns -1.
def isTriangular(num):
if (num < 0):
return False;
# Considering the equation
# n*(n+1)/2 = num. The equation
# is : a(n^2) + bn + c = 0";
c = (-2 * num);
b = 1;
a = 1;
d = (b * b) - (4 * a * c);
if (d < 0):
return -1;
# Find roots of equation
root1 = (-b + math.sqrt(d)) // (2 * a);
root2 = (-b - math.sqrt(d)) // (2 * a);
# checking if root1 is natural
if (root1 > 0 and
math.floor(root1) == root1):
return root1;
# checking if root2 is natural
if (root2 > 0 and
math.floor(root2) == root2):
return root2;
return -1;
# Returns square root of
# x if it is perfect square.
# Else returns -1.
def isPerfectSquare(x):
# Find floating point value
# of square root of x.
sr = math.sqrt(x);
# If square root is an integer
if ((sr - math.floor(sr)) == 0):
return math.floor(sr);
else:
return -1;
# Function to find if the given
# number is sum of the cubes of
# first n natural numbers
def findS(s):
sr = isPerfectSquare(s);
if (sr == -1):
return -1;
return int(isTriangular(sr));
# Driver code
s = 9;
n = findS(s);
if(n == -1):
print("-1");
else:
print(n);
# This code is contributed by mits.
C#
// C# program to check if a
// given number is sum of
// cubes of natural numbers.
using System;
class GFG
{
// Returns root of n(n+1)/2 = num
// if num is triangular (or integer
// root exists). Else returns -1.
static int isTriangular(int num)
{
if (num < 0)
return 0;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) -
(4 * a * c);
if (d < 0)
return -1;
// Find roots of equation
double root1 = (-b + Math.Sqrt(d)) / (2 * a);
double root2 = (-b - Math.Sqrt(d)) / (2 * a);
// checking if root1 is natural
if ((int)(root1) > 0 &&
(int)(Math.Floor(root1)) == (int)(root1))
return (int)(root1);
// checking if root2 is natural
if ((int)(root2) > 0 &&
(int)(Math.Floor(root2)) == (int)(root2))
return (int)(root2);
return -1;
}
// Returns square root of x
// if it is perfect square.
// Else returns -1.
static int isPerfectSquare(double x)
{
// Find floating point
// value of square root of x.
double sr = Math.Sqrt(x);
// If square root
// is an integer
if ((sr - Math.Floor(sr)) == 0)
return (int)(Math.Floor(sr));
else
return -1;
}
// Function to find if the
// given number is sum of
// the cubes of first n
// natural numbers
static int findS(int s)
{
int sr = isPerfectSquare(s);
if (sr == -1)
return -1;
return isTriangular(sr);
}
// Driver code
public static void Main()
{
int s = 9;
int n = findS(s);
if(n == -1)
Console.Write("-1");
else
Console.Write(n);
}
}
// This code is contributed by mits.
PHP
<?php
// PHP 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 integer
// root exists). Else returns -1.
function isTriangular($num)
{
if ($num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
$c = (-2 * $num);
$b = 1;
$a = 1;
$d = ($b * $b) - (4 * $a * $c);
if ($d < 0)
return -1;
// Find roots of equation
$root1 = (-$b + sqrt($d)) /
(2 * $a);
$root2 = (-$b - sqrt($d)) /
(2 * $a);
// checking if root1 is natural
if ($root1 > 0 &&
floor($root1) == $root1)
return $root1;
// checking if root2 is natural
if ($root2 > 0 &&
floor($root2) == $root2)
return $root2;
return -1;
}
// Returns square root of
// x if it is perfect square.
// Else returns -1.
function isPerfectSquare($x)
{
// Find floating point value
// of square root of x.
$sr = sqrt($x);
// If square root is an integer
if (($sr - floor($sr)) == 0)
return floor($sr);
else
return -1;
}
// Function to find if the given
// number is sum of the cubes of
// first n natural numbers
function findS($s)
{
$sr = isPerfectSquare($s);
if ($sr == -1)
return -1;
return isTriangular($sr);
}
// Driver code
$s = 9;
$n = findS($s);
if($n == -1)
echo "-1";
else
echo $n;
// This code is contributed by mits.
?>
JavaScript
<script>
// javascript 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
// integer root exists). Else
// returns -1.
function isTriangular(num)
{
if (num < 0)
return 0;
// Considering the equation
// n*(n+1)/2 = num. The equation
// is : a(n^2) + bn + c = 0";
var c = (-2 * num);
var b = 1, a = 1;
var d = (b * b) - (4 * a * c);
if (d < 0)
return -1;
// Find roots of equation
var root1 = (-b + Math.sqrt(d)) / (2 * a);
var root2 = (-b - Math.sqrt(d)) / (2 * a);
// checking if root1 is natural
if (parseInt( (root1)) > 0 && parseInt( (Math.floor(root1))) == parseInt( (root1)))
return parseInt(root1);
// checking if
// root2 is natural
if (parseInt( (root2)) > 0 && parseInt( (Math.floor(root2))) == parseInt( (root2)))
return parseInt( (root2));
return -1;
}
// Returns square root
// of x if it is perfect
// square. Else returns -1.
function isPerfectSquare(x)
{
// Find floating point
// value of square root of x.
var sr = Math.sqrt(x);
// If square root
// is an integer
if ((sr - Math.floor(sr)) == 0)
return parseInt( (Math.floor(sr)));
else
return -1;
}
// Function to find if the
// given number is sum of
// the cubes of first n
// natural numbers
function findS(s) {
var sr = isPerfectSquare(s);
if (sr == -1)
return -1;
return isTriangular(sr);
}
// Driver code
var s = 9;
var n = findS(s);
if (n == -1)
document.write("-1");
else
document.write(n);
// This code is contributed by Rajput-Ji.
</script>
Time Complexity: O(logn)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem