Find a range of composite numbers of given length in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n. We have to find the range of positive integers, where all the numbers in the range is composite, and the length of the range is n. If there are more than one range, then print any one range. The composite number is a number where it has at least one divisor other than 1 and itself.

As the length of the range is n, then if the first number is a, then the other numbers are a + 1, a + 2, …, a + n – 1, all should be composite. If we see that x!, where x is positive integer, then x has factors of 2, 3, 4, …, p – 1. So p! + i has a factor i, so p! + i must be composite. p! + 2, p! + 3, … p! + p – 1, are all composite. So the range will be [p! + 2, p! + p – 1]

Example

 Live Demo

#include<iostream>
using namespace std;
int fact (int n) {
   if (n == 0)
      return 1;
   return n * fact(n-1);
}
void showRange(int n) {
   int a = fact(n + 2) + 2;
   int b = a + n - 1;
   cout << "[" << a << ", " << b << "]";
}
int main() {
   int n = 3 ;
   showRange(n);
}

Output

[122, 124]
raja
Published on 18-Dec-2019 06:48:45
Advertisements