Minimum number of Square Free Divisors in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an integer N. Find the minimum number of square free divisors.

The factorization of N should comprise of only those divisors that are not full square

Example

If N = 24 then there are 3 square free factors as follows −

Factors = 2 * 6 * 2

Algorithm

  • Find all prime factors upto square root of N
  • Now, consider all prime factors less than or equal to square root of N and for each prime factor find its maximum power in number N (like max power of 2 in 24 is 3)
  • Now, we know that if a prime factor has a power greater than 1 in N, it can’t be grouped with itself (for e.g. 2 has power of 3 in 24, hence 2 x 2 = 4 or 2 x 2 x 2 = 8 can’t occur in the factorization of 24 as both of them are not square free) since it will be divisible by some perfect square
  • But a prime factor grouped with another prime factor (only once) will never be divisible by any perfect square
  • This gives us an intuition that answer will be the maximum of maximum powers of all prime factors in number N

Example

#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
#define MAX 1005
void getPrimes(vector<int>& primes) {
   bool prime[MAX];
   memset(prime, true, sizeof(prime));
   for (int p = 2; p * p < MAX; p++) {
      if (prime[p] == true) {
         for (int i = p * 2; i < MAX; i += p)
            prime[i] = false;
      }
   }
   for (int p = 2; p < MAX; p++)
   if (prime[p])
   primes.push_back(p);
}
int getMinimumSquareFreeDivisors(int n) {
   vector<int> primes;
   getPrimes(primes);
   int maxCnt = 0;
   for (int i = 0; i < primes.size() && primes[i] * primes[i] <= n; i++) {
      if (n % primes[i] == 0) {
         int tmp = 0;
         while (n % primes[i] == 0) {
            tmp++;
            n /= primes[i];
         }
         maxCnt = max(maxCnt, tmp);
      }
   }
   if (maxCnt == 0)
   maxCnt = 1;
   return maxCnt;
}
int main() {
   int n = 24;
   cout << "Minimum number of square free divisors = " << getMinimumSquareFreeDivisors(n) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Minimum number of square free divisors = 3
raja
Published on 22-Nov-2019 10:53:26
Advertisements