📌  相关文章
📜  构造一个由前 N 个自然数组成的数组,使得每个相邻对都是互质的

📅  最后修改于: 2021-10-26 06:34:30             🧑  作者: Mango

给定一个正整数N ,任务是构造一个由前N 个自然数组成的数组,使得数组中的每对相邻元素都是互质数。如果存在多个解决方案,则打印其中任何一个。

例子:

方法:我们的想法是迭代范围[1,N]使用变量i和打印i的值。以下是观察结果:

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to construct an arrary with
// adjacent elements as co-prime numbers
void ConstArrayAdjacentCoprime(int N)
{
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
        // Print i
        cout << i << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 6;
 
    ConstArrayAdjacentCoprime(N);
    return 0;
}


Java
// Java program to implement
// the above approach
class GFG
{
 
    // Function to construct an arrary with
    // adjacent elements as co-prime numbers
    static void ConstArrayAdjacentCoprime(int N)
    {
        // Iterate over the range [1, N]
        for (int i = 1; i <= N; i++)
        {
     
            // Print i
            System.out.print(i + " ");
        }
    }
 
    // Driver Code
    public static void main (String[] args)
    {
      int N = 6;
      ConstArrayAdjacentCoprime(N);
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 program to implement
# the above approach
 
# Function to construct an arrary with
# adjacent elements as co-prime numbers
def ConstArrayAdjacentCoprime(N):
 
    # Iterate over the range [1, N]
    for i in range(1, N + 1):
       
        # Print i
        print(i, end = " ")
 
# Driver Code
if __name__ == "__main__" :
 
    N = 6
 
    ConstArrayAdjacentCoprime(N)
 
# This code is contributed by AnkitRai01


C#
// C# program to implement
// the above approach 
using System;
 
class GFG{
  
// Function to construct an arrary with
// adjacent elements as co-prime numbers
static void ConstArrayAdjacentCoprime(int N)
{
     
    // Iterate over the range [1, N]
    for(int i = 1; i <= N; i++)
    {
         
        // Print i
        Console.Write(i + " ");
    }
}
 
// Driver Code
public static void Main ()
{
    int N = 6;
     
    ConstArrayAdjacentCoprime(N);
}
}
 
// This code is contributed by susmitakundugoaldanga


Javascript


输出:
1 2 3 4 5 6

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