Maximum number of unique prime factors in C++

Given the task is to find the maximum number of unique prime factors a number can have in the range of [1, N] where N is given.

Let’s now understand what we have to do using an example −

Input − N=100

Output − 3

Explanation − Let us take 30 in the range of [1, 100]

30 = 3 * 2 * 5 = unique prime factors. Therefore, in the range of [1, 100] a maximum of 3 unique factors can be found.

Input − N=300

Output − 4

Approach used in the below program as follows

• In function MaxPrime() we will first check if (N < 2). If so then simply return zero, otherwise proceed.

• Then we will use the sieve of Eratosthenes to find out all the prime numbers before the given number N.

• Initialize two variables pro=1 and max=0 of type int to store the product and the final answer respectively.

• Inside the sieve of Eratosthenes we will multiply the first set of prime numbers until the product remains smaller than N by writing − pro=*p;

• Check if (pro > N). If so then return max and add 1 to max.

• Outside the sieve, also return max.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int MaxPrime(int N){
if (N < 2)
return 0;
// Using Sieve of Eratosthenes
bool Arr[N+1];
memset(Arr, true, sizeof(Arr));
int pro = 1, max = 0;
for (int p=2; p*p<=N; p++){
if (Arr[p] == true){
for (int i=p*2; i<=N; i += p)
Arr[i] = false;
/*Multiply first set of prime numbers while product remains smaller than N*/
pro *= p;
if (pro > N)
return max;
max++;
}
}
return max;
}
//Main function
int main(){
int N = 300;
cout << MaxPrime(N);
return 0;
}

Output

If we run the above code we will get the following output −

4