Given a number n , the task is to generate a non-decreasing sequence of n integers such that no two integers divides each other.
Example :
Input : 3 Output : 2 9 15 Explanation : In the above non-decreasing sequence no two integers divides each other as (2 , 9) , (2 , 15) , (9 , 15). Input : 5 Output : 11 14 20 27 31
Approach :
One of the simplest way to solve this problem is to generate exactly n prime number using Sieve of eratosthenes as no two prime numbers divide each other. But a more subtle approach is based on the observation that for large enough n the consecutive numbers always satisfy the given conditions for example 2*n + 0 , 2*n + 1 , 2*n + 2 , …. 2*n + (n-1) ,this works because the smallest multiple for 2*n is 2*2*n It is not possible to obtain smaller multiple than that one and there are 4*n – 2*n = 2*n integers between them which do not divide each other and we need only n then this solution will always work.
Implementation :
// c++ program to print a
// non-decreasing sequence of n integers such
// that no two numbers divide each other
#include <bits/stdc++.h>
using namespace std;
int main()
{
// input integer
int n = 10;
// print numbers from n+1 upto 2*n
for (int i = n + 1; i <= 2 * n; i++)
cout << i << " ";
return 0;
}
Output : 11 12 13 14 15 16 17 18 19 20
Complexity Analysis:
Time Complexity : O(n)
Space Complexity : O(1)