📜  生成一个备用奇偶序列,该序列具有所有连续对的和作为完美平方

📅  最后修改于: 2021-05-04 09:39:53             🧑  作者: Mango

给定一个整数N ,任务是按递增顺序打印一个长度为N的序列,该序列由交替的奇数和偶数组成,以使任意两个连续项的和成为一个完美的平方。

例子:

方法:可以根据上述示例的观察结果解决给定问题,对于整数N ,序列的形式为1、8、17、32、49 ,依此类推。因此,可以通过以下公式计算N项:

因此,要解决该问题,请遍历范围[1,N]以使用上述公式计算并打印序列的每个项。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to print the
// required sequence
void findNumbers(int n)
{
    int i = 0;
    while (i <= n) {
 
        // Print ith odd number
        cout << 2 * i * i + 4 * i
                    + 1 + i % 2
             << " ";
        i++;
    }
}
 
// Driver Code
int main()
{
    int n = 6;
    findNumbers(n);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
     
// Function to print the
// required sequence
static void findNumbers(int n)
{
    int i = 0;
    while (i <= n)
    {
 
        // Print ith odd number
        System.out.print(2 * i * i + 4 * i +
                         1 + i % 2 + " ");
        i++;
    }
}
 
// Driver code
public static void main (String[] args)
{
    int n = 6;
     
    // Function call
    findNumbers(n);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to implement
# the above approach
  
# Function to prthe
# required sequence
def findNumbers(n):
     
    i = 0
    while (i <= n):
  
        # Print ith odd number
        print(2 * i * i + 4 * i +
              1 + i % 2, end = " ")
               
        i += 1
     
# Driver Code
n = 6
 
findNumbers(n)
 
# This code is contributed by sanjoy_62


C#
// C# program to implement
// the above approach
using System;
  
class GFG{
      
// Function to print the
// required sequence
static void findNumbers(int n)
{
    int i = 0;
    while (i <= n)
    {
         
        // Print ith odd number
        Console.Write(2 * i * i + 4 * i +
                      1 + i % 2 + " ");
 
        i++;
    }
}
  
// Driver code
public static void Main ()
{
    int n = 6;
      
    // Function call
    findNumbers(n);
}
}
  
// This code is contributed by sanjoy_62


Javascript


输出:
1 8 17 32 49 72 97

时间复杂度: O(N)
辅助空间: O(1)