# Count all the numbers less than 10^6 whose minimum prime factor is N C++

C++Server Side ProgrammingProgramming

We are given a prime number let’s say, num and the task is to calculate the count of all the numbers less than 10^6 whose minimum prime factor is equal to num.

## For Example

Input − num = 7
Output − Number of prime factors = 38095

Input − num = 3
Output − Number of prime factors = 16666

Approach used in the below program is as follows

• Input the number let’s say num

• Start the loop, from i to 2 and i should be less than or equals to max value and increment the value of i

• Inside the loop, check if s_prime[i] = 0

• Create the loop, set the j to i * 2 and j should be less than equals to max and set j to j + i

• Now check, if s_prime[j] = 1

• Set s_prime[j] = 1

• Increment s_count[i] by 1

• Print the result

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000
// a sieve for prime number and
// to count the number of prime
int s_prime[MAX + 4] = { 0 }, s_count[MAX + 4] = { 0 };
void create_sieve(){
// As 1 is not a prime number
s_prime[1] = 1;
// creating the sieve
for (int i = 2; i <= MAX; i++){
// if i is a prime number
if (s_prime[i] == 0){
for (int j = i * 2; j <= MAX; j += i){
// if i is the least prime factor
if (s_prime[j] == 0){
// The number j is not a prime
s_prime[j] = 1;
// counting the numbers whose least prime factor
// is i
s_count[i]++;
}
}
}
}
}
int main(){
// create the sieve
create_sieve();
int N = 7;
cout << "Number of prime factors = " << (s_count[N] + 1) << endl;
N = 3;
cout << "Number of prime factors = " << (s_count[N] + 1) << endl;
return 0;
}

## Output

If we run the above code it will generate the following output −

Number of prime factors = 38095
Number of prime factors = 166667
Published on 15-May-2020 12:37:37