Generate Array of distinct elements with GCD as 1 and no Coprime pair
Last Updated :
23 Jul, 2025
Given an integer N, the task is to generate an array of N distinct integers. Such that the GCD of all the elements of the array is 1, but no pair of elements is co-prime i.e., for any pair (A[i], A[j]) of array GCD(A[i], A[j]) ≠ 1.
Note: If more than 1 answers are possible, print any of them.
Examples:
Input: N = 4
Output: 30 70 42 105
Explanation: GCD(30, 70, 42, 105) = 1.
GCD(30, 70) = 10, GCD(30, 42) = 6, GCD(30, 105) = 15, GCD(70, 42) = 14, GCD(70, 105) = 35, GCD(42, 105) = 21.
Hence, it can be seen that GCD of all elements is 1, whereas GCD of all possible pairs is greater than 1.
Input: N = 6
Output: 10 15 6 12 24 48
Approach: The problem can be solved based on the following observation:
Suppose A1, A2, A3 . . . AN are N prime numbers. Let their product be P, i.e. P = A1 * A2 * A3 . . .*AN.
Then, the sequence P/A1 , P/A2 . . . P/AN = (A2 * A3 . . . AN), (A1 * A3 . . . AN), . . ., (A1 * A2 . . . AN-1)
This sequence have at least one common factor between any pair of elements but the overall GCD is 1
This can be done following the steps given below:
- If N = 2, return -1, as no such sequence is possible for N = 2.
- Store the first N primes using the Sieve of Eratosthenes (say in a vector v).
- Calculate the product of all elements of vector "v" and store it in a variable (say "product").
- Now, iterate from i = 0 to N-1 and at each iteration store the ith element of answer as (product/v[i]).
- Return the resultant vector.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
const int M = 100001;
bool primes[M + 1];
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
void printArray(int N)
{
// Such sequence is not possible for N=2
if (N == 2) {
cout << -1 << endl;
return;
}
// storing primes upto M using sieve
for (int i = 0; i < M; i++)
primes[i] = 1;
primes[0] = 0;
primes[1] = 0;
for (int i = 2; i * i <= M; i++) {
if (primes[i] == 1) {
for (int j = i * i; j <= M;
j += i) {
primes[j] = 0;
}
}
}
// Storing first N primes in vector v
vector<int> v;
for (int i = 0; i < M; i++) {
if (v.size() < N
&& primes[i] == 1) {
v.push_back(i);
}
}
// Calculating product of
// first N prime numbers
int product = 1;
vector<int> answer;
for (auto it : v) {
product *= it;
}
// Calculating answer sequence
for (int i = 0; i < N; i++) {
int num = product / v[i];
answer.push_back(num);
}
// Printing the answer
for (int i = 0; i < N; i++) {
cout << answer[i] << " ";
}
}
// Driver Code
int32_t main()
{
int N = 4;
// Function call
printArray(N);
return 0;
}
Java
// Java code to implement the approach
import java.util.ArrayList;
class GFG {
static int M = 100001;
static int[] primes = new int[M + 1];
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
static void printArray(int N)
{
// Such sequence is not possible for N=2
if (N == 2) {
System.out.println(-1);
return;
}
// storing primes upto M using sieve
for (int i = 0; i < M; i++)
primes[i] = 1;
primes[0] = 0;
primes[1] = 0;
for (int i = 2; i * i <= M; i++) {
if (primes[i] == 1) {
for (int j = i * i; j <= M; j += i) {
primes[j] = 0;
}
}
}
// Storing first N primes in arraylist v
ArrayList<Integer> v = new ArrayList<Integer>();
for (int i = 0; i < M; i++) {
if (v.size() < N && primes[i] == 1) {
v.add(i);
}
}
// Calculating product of
// first N prime numbers
int product = 1;
ArrayList<Integer> answer
= new ArrayList<Integer>();
;
for (int i = 0; i < v.size(); i++) {
product *= v.get(i);
}
// Calculating answer sequence
for (int i = 0; i < N; i++) {
int num = product / v.get(i);
answer.add(num);
}
// Printing the answer
for (int i = 0; i < N; i++) {
System.out.print(answer.get(i) + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
// Function call
printArray(N);
}
}
// This code is contributed by phasing.
Python3
# Python code to implement the approach
M = 100001
primes = [0]*(M + 1)
# Function to form an array such that
# pairwise gcd of all elements is not 1
# and gcd of whole sequence is 1
def printArrayint(N):
# Such sequence is not possible for N=2
if N == 2:
print(-1)
return
# storing primes upto M using sieve
for i in range(M):
primes[i] = 1
primes[0] = 0
primes[1] = 0
i = 2
while i * i <= M:
if primes[i] == 1:
j = i*i
while j <= M:
primes[j] = 0
j += i
i += 1
# Storing first N primes in vector v
v = []
for i in range(M):
if len(v) < N and primes[i] == 1:
v.append(i)
# Calculating product of
# first N prime numbers
product = 1
answer = []
for it in v:
product *= it
# Calculating answer sequence
for i in range(N):
num = product // v[i]
answer.append(num)
# Printing the answer
for i in range(N):
print(answer[i], end=" ")
# Driver Code
if __name__ == "__main__":
N = 4
printArrayint(N)
# This code is contributed by amnindersingh1414.
C#
// C# code to implement the approach
using System;
using System.Collections;
class GFG {
static int M = 100001;
static int[] primes = new int[M + 1];
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
static void printArray(int N)
{
// Such sequence is not possible for N=2
if (N == 2) {
Console.WriteLine(-1);
return;
}
// storing primes upto M using sieve
for (int i = 0; i < M; i++)
primes[i] = 1;
primes[0] = 0;
primes[1] = 0;
for (int i = 2; i * i <= M; i++) {
if (primes[i] == 1) {
for (int j = i * i; j <= M; j += i) {
primes[j] = 0;
}
}
}
// Storing first N primes in vector v
ArrayList v = new ArrayList();
for (int i = 0; i < M; i++) {
if (v.Count < N && primes[i] == 1) {
v.Add(i);
}
}
// Calculating product of
// first N prime numbers
int product = 1;
ArrayList answer = new ArrayList();
foreach(int it in v) { product *= (int)it; }
// Calculating answer sequence
for (int i = 0; i < N; i++) {
int num = product / (int)v[i];
answer.Add(num);
}
// Printing the answer
for (int i = 0; i < N; i++) {
Console.Write(answer[i] + " ");
}
}
// Driver Code
public static void Main()
{
int N = 4;
// Function call
printArray(N);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code for the above approach
let M = 100001;
let primes = new Array(M + 1);
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
function printArray(N)
{
// Such sequence is not possible for N=2
if (N == 2) {
document.write(-1 + "<br>")
return;
}
// storing primes upto M using sieve
for (let i = 0; i < M; i++)
primes[i] = 1;
primes[0] = 0;
primes[1] = 0;
for (let i = 2; i * i <= M; i++) {
if (primes[i] == 1) {
for (let j = i * i; j <= M;
j += i) {
primes[j] = 0;
}
}
}
// Storing first N primes in vector v
let v = [];
for (let i = 0; i < M; i++) {
if (v.length < N
&& primes[i] == 1) {
v.push(i);
}
}
// Calculating product of
// first N prime numbers
let product = 1;
let answer = [];
for (let it of v) {
product *= it;
}
// Calculating answer sequence
for (let i = 0; i < N; i++) {
let num = Math.floor(product / v[i]);
answer.push(num);
}
// Printing the answer
for (let i = 0; i < N; i++) {
document.write(answer[i] + " ")
}
}
// Driver Code
let N = 4;
// Function call
printArray(N);
// This code is contributed by Potta Lokesh
</script>
Time Complexity : O(M*(log(logM))) where M is a large positive number [here, 100000]
Auxiliary Space : O(M)
Better Approach: The above approach will fail for larger values of N, as the product of more than 15 primes can not be stored. This can be avoided based on the following observation:
Fix the first three distinct numbers with all possible products formed taking two among first three primes (say the numbers formed are X, Y and Z).
Then for the next elements keep on multiplying any one (say X) by one of the primes (say it becomes X') and changing X to X'.
As the GCD of X, Y and Z is 1 the overall GCD will be one but no two elements will be coprime to each other.
For own convenience use the first 3 primes 2, 3, 5 and make the first 3 numbers as 10, 15, 6, and the others by multiplying with 2 i.e. 12, 24, 48, . . .
Below is the implementation of the above approach.
C++
// C++ code for above approach
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
void printArray(int N)
{
if (N == 1) {
cout << 2 << endl;
}
// Such sequence is not possible for N = 2
if (N == 2) {
cout << -1 << endl;
return;
}
int ans[N];
// Initializing initial 3 terms
// of the sequence
ans[0] = 10, ans[1] = 15, ans[2] = 6;
// Calculating next terms of the sequence
// by multiplying previous terms by 2
for (int i = 3; i < N; i++) {
ans[i] = 2LL * ans[i - 1];
}
// Printing the final sequence
for (int i = 0; i < N; i++) {
cout << ans[i] << " ";
}
}
// Driver Code
int32_t main()
{
int N = 4;
// Function call
printArray(N);
return 0;
}
Java
// JAVA code for above approach
import java.util.*;
class GFG {
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
public static void printArray(int N)
{
if (N == 1) {
System.out.println(2);
}
// Such sequence is not possible for N = 2
if (N == 2) {
System.out.println(-1);
return;
}
int ans[] = new int[N];
// Initializing initial 3 terms
// of the sequence
ans[0] = 10;
ans[1] = 15;
ans[2] = 6;
// Calculating next terms of the sequence
// by multiplying previous terms by 2
for (int i = 3; i < N; i++) {
ans[i] = 2 * ans[i - 1];
}
// Printing the final sequence
for (int i = 0; i < N; i++) {
System.out.print(ans[i] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
// Function call
printArray(N);
}
}
// This code is contributed by Taranpreet
Python3
# Python code for above approach
# Function to form an array such that
# pairwise gcd of all elements is not 1
# and gcd of whole sequence is 1
def printArray(N):
if (N == 1):
print(2)
# Such sequence is not possible for N = 2
if (N == 2):
print(-1)
return
ans = [0]*N
# Initializing initial 3 terms
# of the sequence
ans[0] = 10
ans[1] = 15
ans[2] = 6
# Calculating next terms of the sequence
# by multiplying previous terms by 2
for i in range(3, N):
ans[i] = 2 * ans[i - 1]
# Printing the final sequence
for i in range(N):
print(ans[i], end=" ")
# Driver Code
if __name__ == '__main__':
N = 4
printArray(N)
# This code is contributed by amnindersingh1414.
C#
// C# code to implement the above approach
using System;
class GFG
{
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
public static void printArray(int N)
{
if (N == 1) {
Console.Write(2);
}
// Such sequence is not possible for N = 2
if (N == 2) {
Console.Write(-1);
return;
}
int[] ans = new int[N];
// Initializing initial 3 terms
// of the sequence
ans[0] = 10;
ans[1] = 15;
ans[2] = 6;
// Calculating next terms of the sequence
// by multiplying previous terms by 2
for (int i = 3; i < N; i++) {
ans[i] = 2 * ans[i - 1];
}
// Printing the final sequence
for (int i = 0; i < N; i++) {
Console.Write(ans[i] + " ");
}
}
// Driver code
public static void Main()
{
int N = 4;
// Function call
printArray(N);
}
}
// This code is contributed by sanjoy_62.
JavaScript
<script>
// Javascript code for above approach
// Function to form an array such that
// pairwise gcd of all elements is not 1
// and gcd of whole sequence is 1
function printArray( N)
{
if (N == 1) {
document.write(2);
}
// Such sequence is not possible for N = 2
if (N == 2) {
document.write(-1);
return;
}
let ans = new Array(N);
// Initializing initial 3 terms
// of the sequence
ans[0] = 10;
ans[1] = 15;
ans[2] = 6;
// Calculating next terms of the sequence
// by multiplying previous terms by 2
for (let i = 3; i < N; i++) {
ans[i] = 2 * ans[i - 1];
}
// Printing the final sequence
for (let i = 0; i < N; i++) {
document.write(ans[i] + " ");
}
}
// Driver Code
let N = 4;
// Function call
printArray(N);
// This code is contributed by jana_sayantan.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem