Construct an Array of size N whose sum of cube of all elements is a perfect square
Given an integer N, the tasks is to construct a sorted array arr of size N, such that the sum of cube of all elements is a perfect square, i.e. , where X is an integer.
Input: N = 5
Output: 1 2 3 4 5
Sum of cube of all elements = 1 + 8 + 27 + 64 + 125 = 225
which is a perfect square number.
Input: N = 1
- The sum of cubes of first N natural number is given by:
- So, the summation is itself, a perfect square of the integer
- Therefore , which is nothing but sum of N natural numbers.
- So, just print the first N natural numbers to construct the array.
Below is the implementation of the above approach:
1 2 3 4 5
Time Complexity: O(N)
Auxiliary Space: O(1)
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.