C++ code to find sorted array with non-divisibility conditions


Suppose we have a number n. Consider we are going to form an array A with n elements. A is sorted in ascending order and all elements are distinct. For every i from 2 to n (considering array index starts from 1) A[i] is not divisible by A[i-1].

So, if the input is like n = 7, then the output will be [2, 3, 4, 5, 6, 7, 8]

To solve this, we will follow these steps −

for initialize i := 2, when i <= n + 1, update (increase i by 1), do:
   print i

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int n){
   for (int i = 2; i <= n + 1; i++){
      printf("%d, ", i);
   }
}
int main(){
   int n = 7;
   solve(n);
}

Input

7

Output

2, 3, 4, 5, 6, 7, 8,

Updated on: 15-Mar-2022

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements