Construct an array of first N natural numbers such that every adjacent pair is coprime
Last Updated :
09 Dec, 2022
Given a positive integer N, the task is to construct an array consisting of first N natural numbers such that each pair of adjacent elements in the array is a co-prime. If multiple solutions exist, then print any one of them.
Examples:
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
Approach: The idea is to iterate over the range [1, N] using variable i and print the value of i. Following are the observations:
GCD(i, i + 1) = 1
Therefore, for all possible value of i the pair (i, i + 1) are coprime numbers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void ConstArrayAdjacentCoprime( int N)
{
for ( int i = 1; i <= N; i++)
cout << i << " " ;
}
int main()
{
int N = 6;
ConstArrayAdjacentCoprime(N);
return 0;
}
|
C
#include <stdio.h>
void ConstArrayAdjacentCoprime( int N)
{
for ( int i = 1; i <= N; i++)
printf ( "%d " , i);
}
int main()
{
int N = 6;
ConstArrayAdjacentCoprime(N);
return 0;
}
|
Java
public class GFG
{
static void ConstArrayAdjacentCoprime( int N)
{
for ( int i = 1 ; i <= N; i++)
{
System.out.print(i + " " );
}
}
public static void main (String[] args)
{
int N = 6 ;
ConstArrayAdjacentCoprime(N);
}
}
|
Python3
def ConstArrayAdjacentCoprime(N):
for i in range ( 1 , N + 1 ):
print (i, end = " " )
if __name__ = = "__main__" :
N = 6
ConstArrayAdjacentCoprime(N)
|
C#
using System;
class GFG{
static void ConstArrayAdjacentCoprime( int N)
{
for ( int i = 1; i <= N; i++)
{
Console.Write(i + " " );
}
}
public static void Main ()
{
int N = 6;
ConstArrayAdjacentCoprime(N);
}
}
|
Javascript
<script>
function ConstArrayAdjacentCoprime(N)
{
for (let i = 1; i <= N; i++)
{
document.write(i + " " );
}
}
let N = 6;
ConstArrayAdjacentCoprime(N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...