A Square pyramidal number represents sum of squares of first natural numbers. First few Square pyramidal numbers are 1, 5, 14, 30, 55, 91, 140, 204, 285, 385, 506, …
Geometrically these numbers represent number of spheres to be stacked to form a pyramid with square base. Please see this Wiki image for more clarity.
Given a number s (1 <= s <= 1000000000). If s is sum of the squares of the first n natural numbers then print n, otherwise print -1.
Input : 14 Output : 3 Explanation : 1*1 + 2*2 + 3*3 = 14 Input : 26 Output : -1
A simple solution is to run through all numbers starting from 1, compute current sum. If current sum is equal to given sum, then we return true, else false.
We can write solutions as
k * (k + 1) * (2*k + 1) / 6 = s
k * (k + 1) * (2*k + 1) – 6s = 0
We can find roots of above cubic equation using Newton Raphson Method, then check if root is integer or not.
- Pentagonal Pyramidal Number
- Difference between sum of the squares of first n natural numbers and square of sum
- Find the side of the squares which are lined in a row, and distance between the centers of first and last square is given
- Check if a number is perfect square without finding square root
- Minimum number of squares whose sum equals to given number n
- Number of perfect squares between two given numbers
- Count number of squares in a rectangle
- Paper Cut into Minimum Number of Squares
- Number of ways of writing N as a sum of 4 squares
- Check whether a number can be represented by sum of two squares
- Program to find number of squares in a chessboard
- Number of squares of maximum area in a rectangle
- Count number less than N which are product of perfect squares
- Number of unique rectangles formed using N unit squares
- Find minimum number to be divided to make a number a perfect square
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.