- Related Questions & Answers
- Maximum GCD of N integers with given product in C++
- Maximum Product of Word Lengths in C++
- Maximum Product of Three Numbers in C++
- Maximum Possible Product in Array after performing given Operations in C++
- Maximum product subset of an array in C++
- Maximum product of an increasing subsequence in C++
- Find GCD of factorial of elements of given array in C++
- Maximum product of subsequence of size k in C++
- Maximum Product Subarray | Added negative product case in C++
- Find the Number of Maximum Product Quadruples in C++
- Maximum product of an increasing subsequence in C++ Program
- Maximum product subset of an array in C++ program
- Maximum number of removals of given subsequence from a string in C++
- Maximum and Minimum Product Subsets in C++
- Maximum Product Cutting | DP-36 in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 a_{1}, a_{2}, … a_{n}. Then ai is multiple of g, and P is (a_{1} * a_{2} * … * a_{n}) must be a multiple of g^{n}. The answer is max g such that g^{n} mod P = 0. Now suppose P = k1^{p1} * k2^{p1} * … * kn^{pn}. g must be of the form like this, then to maximize g, we have to choose p_{i} = p_{i} / N.

#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); }

MAX GCD: 2

Advertisements