给定一个正整数N ,任务是构造一个由前N个自然数组成的数组,以使该数组中的每对相邻元素都是互质数。如果存在多个解决方案,则打印其中任何一种。
例子:
Input: N = 4
Output: 4 1 3 2
Explanation:
All possible adjacent pairs of the array are { (4, 1), (1, 3), (3, 2) }
Since all adjacent pairs of the array are co-prime, the required output is 4 1 3 2.
Input: N = 7
Output: 3 4 5 7 6 1 2
方法:我们的想法是迭代范围[1,N]使用变量i和打印i的值。以下是观察结果:
GCD(i, i + 1) = 1
Therefore, for all possible value of i the pair (i, i + 1) are coprime numbers.
下面是上述方法的实现:
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
输出:
1 2 3 4 5 6
时间复杂度: O(N)
辅助空间: O(1)