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

📅  最后修改于: 2021-05-17 05:56:15             🧑  作者: 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)