📌  相关文章
📜  构造一个大小为 N 的数组,其所有元素的立方和是一个完全平方数

📅  最后修改于: 2021-09-07 02:23:18             🧑  作者: Mango

给定一个整数N ,任务是构造一个大小为N的排序数组arr[] ,使得所有元素的立方和是一个完美的平方,即\sum_{}A_i^3=X^2  ,其中 X 是整数。

例子:

解决方法:

  1. 前 N 个自然数的立方和由下式给出:
    (\frac{N \times(N+1)}{2})^2
  2. 所以,总和本身就是整数的完美平方X^2&=(\frac{N \times(N+1)}{2})^2
  3. 所以X&=(\frac{N \times(N+1)}{2})  ,它只不过是 N 个自然数的和。
  4. 因此,只需打印前 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)