Square pyramidal number (Sum of Squares)
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.
An alternate solution is to use Newton Raphson Method.
We know sum of squares of first n natural numbers is n * (n + 1) * (2*n + 1) / 6.
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.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.