Maximum GCD from Given Product of Unknowns in C++

C++Server Side ProgrammingProgramming

Suppose we two integers N and P. The P is the product of N unknown integers. We have to find the GCD of those integers. There can be different groups of integers possible, that will give the same result. Here we will produce GCD, which is maximum among all possible groups. Suppose N = 3, and P = 24, then different groups will be like {1, 1, 24}, {1, 2, 12}, {1, 3, 8}, {1, 4, 6}, {2, 2, 6}, {2, 3, 4}. The GCDs are: 1, 1, 1, 1, 2, 1. So answer is 2 here.

The technique us like, suppose g is the GCD of a1, a2, … an. Then ai is multiple of g, and P is (a1 * a2 * … * an) must be a multiple of gn. The answer is max g such that gn mod P = 0. Now suppose P = k1p1 * k2p1 * … * knpn. g must be of the form like this, then to maximize g, we have to choose pi = pi / N.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
long getMaxGCD(long n, long p) {
   int count = 0;
   long gcd = 1;
   while (p % 2 == 0) {
      p >>= 1;
      count++; //number of times P divided by 2
   }
   if (count > 0) //if p has some 2s, then
      gcd = gcd* (long)pow(2, count / n);
   for (long i = 3; i <= sqrt(p); i += 2) { //check for all numbers after 2
      count = 0;
      while (p % i == 0) {
         count++;
         p = p / i;
      }
      if (count > 0) {
         gcd = gcd* (long)pow(i, count / n);
      }
   }
   // If n in the end is a prime number
   if (p > 2)
      gcd = gcd* (long)pow(p, 1 / n);
   return gcd;
}
int main() {
   long n = 3;
   long p = 24;
   cout << "MAX GCD: " << getMaxGCD(n, p);
}

Output

MAX GCD: 2
raja
Published on 21-Oct-2019 06:56:39
Advertisements