📌  相关文章
📜  构造一个数组,使所有元素的立方和成为一个完美的正方形

📅  最后修改于: 2021-04-23 06:35:41             🧑  作者: Mango

给定数组N的大小,任务是用正整数元素构造大小N的数组,以使该数组所有元素的立方和成为一个完美的正方形。
注意:允许对整数进行重排。
例子:

方法:这个想法是构造大小为N的数组,其中N包含第一个N个自然数。如果仔细观察,

下面是上述方法的实现。

C++
// C++ program to construct an array
// that cube sum of all element
// is a perfect square
 
#include 
using namespace std;
 
// Function to create
// and print the array
void constructArray(int N)
{
    int arr[N];
 
    // initialise the array of size N
    for (int i = 1; i <= N; i++) {
        arr[i - 1] = i;
    }
 
    // Print the array
    for (int i = 0; i < N; i++) {
        cout << arr[i] << ", ";
    }
}
 
// Driver code
int main()
{
    int N = 6;
 
    constructArray(N);
 
    return 0;
}


Java
// Java program to construct array
// that cube sum of all element
// is a perfect square
import java.util.*;
 
class GFG{
 
// Function to create
// and print the array
static void constructArray(int N)
{
    int arr[] = new int[N];
 
    // Initialise the array of size N
    for(int i = 1; i <= N; i++)
    {
       arr[i - 1] = i;
    }
 
    // Print the array
    for(int i = 0; i < N; i++)
    {
        System.out.print(arr[i] + ", ");
    }
}
 
// Driver code
public static void main(String[] args)
{
    int N = 6;
 
    constructArray(N);
}
}
 
// This code is contributed by AbhiThakur


Python3
# Python3 program to construct
# array that cube sum of all 
# element is a perfect square
 
# Function to create
# and print the array
def constructArray(N):
 
    arr = [0] * N
 
    # Initialise the array of size N
    for i in range(1, N + 1):
        arr[i - 1] = i;
     
    # Print the array
    for i in range(N):
        print(arr[i], end = ", ")
 
# Driver code
N = 6;
constructArray(N);
 
# This code is contributed by grand_master


C#
// C# program to construct array
// that cube sum of all element
// is a perfect square
using System;
 
class GFG{
 
// Function to create
// and print the array
static void constructArray(int N)
{
    int []arr = new int[N];
 
    // Initialise the array of size N
    for(int i = 1; i <= N; i++)
    {
       arr[i - 1] = i;
    }
 
    // Print the array
    for(int i = 0; i < N; i++)
    {
       Console.Write(arr[i] + ", ");
    }
}
 
// Driver code
public static void Main()
{
    int N = 6;
 
    constructArray(N);
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
1, 2, 3, 4, 5, 6,

时间复杂度: O(N) ,其中N是数组的大小。
空间复杂度: O(1)