![]() |
VOOZH | about |
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.
2
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)
2
Time Complexity: O(logn)
Auxiliary Space: O(1)