给定一个整数N ,任务是构造一个大小为N的排序数组arr[] ,使得所有元素的立方和是一个完美的平方,即 ,其中 X 是整数。
例子:
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
解决方法:
- 前 N 个自然数的立方和由下式给出:
- 所以,总和本身就是整数的完美平方
- 所以 ,它只不过是 N 个自然数的和。
- 因此,只需打印前 N 个自然数来构造数组。
下面是上述方法的实现:
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Function to construct an array
// of size N
void constructArray(int N)
{
for (int i = 1; i <= N; i++) {
// Prints the first N
// natural numbers
cout << i << " ";
}
}
// Driver code
int main()
{
int N = 5;
constructArray(N);
return 0;
}
Java
// Java implementation of the
// above approach
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 Code
public 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 Code
public static void Main(String[] args)
{
int N = 5;
constructArray(N);
}
}
// This code is contributed by sapnasingh4991
Javascript
输出:
1 2 3 4 5
时间复杂度: O(N)
辅助空间: O(1)