Find minimum number to be divided to make a number a perfect square in C++


Suppose we have a number N. We have to find minimum number that divide N to make it perfect square. So if N = 50, then minimum number is 2, as 50 / 2 = 25, and 25 is a perfect square.

A number is perfect square if it has even number of different factors. So we will try to find the prime factors of N, and find each prime factor power. Find and multiply all prime factors whose power is odd.

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int findMinimumNumberToDivide(int n) {
   int prime_factor_count = 0, min_divisor = 1;
   while (n%2 == 0) {
      prime_factor_count++;
      n /= 2;
   }
   if (prime_factor_count %2)
   min_divisor *= 2;
   for (int i = 3; i <= sqrt(n); i += 2) {
      prime_factor_count = 0;
      while (n%i == 0) {
         prime_factor_count++;
         n /= i;
      }
      if (prime_factor_count%2)
      min_divisor *= i;
   }
   if (n > 2)
   min_divisor *= n;
   return min_divisor;
}
int main() {
   int n = 108;
   cout << "Minimum number to divide is: " << findMinimumNumberToDivide(n) << endl;
}

Output

Minimum number to divide is: 3

Updated on: 18-Dec-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements