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.
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: 1
Solution Approach:
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
void constructArray( int N)
{
for ( int i = 1; i <= N; i++) {
cout << i << " " ;
}
}
int main()
{
int N = 5;
constructArray(N);
return 0;
}
|
Java
import java.io.*;
public class GFG{
public static void constructArray( int N)
{
for ( int i = 1 ; i <= N; i++)
{
System.out.print(i + " " );
}
}
public static void main(String[] args)
{
int N = 5 ;
constructArray(N);
}
}
|
Python3
def constructArray(N):
for i in range ( 1 , N + 1 ):
print (i, end = ' ' )
if __name__ = = '__main__' :
N = 5
constructArray(N)
|
C#
using System;
class GFG{
public static void constructArray( int N)
{
for ( int i = 1; i <= N; i++)
{
Console.Write(i + " " );
}
}
public static void Main(String[] args)
{
int N = 5;
constructArray(N);
}
}
|
Javascript
<script>
function constructArray(N)
{
for (let i = 1; i <= N; i++)
{
document.write(i + " " );
}
}
let N = 5;
constructArray(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
20 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...