# Construct an Array of size N whose sum of cube of all elements is a perfect square

Last Updated : 20 Dec, 2022

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.

Examples:

Input: N = 5
Output: 1 2 3 4 5
Explanation
Sum of cube of all elements = 1 + 8 + 27 + 64 + 125 = 225
which is a perfect square number.

Input: N = 1
Output:

Solution Approach:

1. The sum of cubes of first N natural number is given by:
2. So, the summation is itself, a perfect square of the integer
3. Therefore , which is nothing but sum of N natural numbers.
4. So, just print the first N natural numbers to construct the array.

Below is the implementation of the above approach:

## C++

 // C++ implementation of the// above approach #include using namespace std; // Function to construct an array// of size Nvoid constructArray(int N){    for (int i = 1; i <= N; i++) {         // Prints the first N        // natural numbers        cout << i << " ";    }} // Driver codeint main(){    int N = 5;    constructArray(N);    return 0;}

## Java

 // Java implementation of the // above approachimport java.io.*;public class GFG{     // Function to construct an array // of size N public static void constructArray(int N) {     for(int i = 1; i <= N; i++)    {                // Prints the first N        // natural numbers        System.out.print(i + " ");    } }  // Driver Codepublic static void main(String[] args){    int N = 5;    constructArray(N); }} // This code is contributed by divyeshrabadiya07

## Python3

 # Python3 implementation of the # above approach  # Function to construct an array # of size N def constructArray(N):         for i in range(1, N + 1):                 # Prints the first N         # natural numbers         print(i, end = ' ')          # Driver code if __name__=='__main__':         N = 5         constructArray(N) # This code is contributed by rutvik_56

## C#

 // C# implementation of the // above approach using System;class GFG{     // Function to construct an array // of size N public static void constructArray(int N) {     for(int i = 1; i <= N; i++)    {                  // Prints the first N         // natural numbers         Console.Write(i + " ");    } }  // Driver Codepublic static void Main(String[] args){    int N = 5;    constructArray(N); }} // This code is contributed by sapnasingh4991

## Javascript

 

Output:
1 2 3 4 5

Time Complexity: O(N)
Auxiliary Space: O(1)

Previous
Next