
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum GCD of N integers with given product in C++
Suppose we two integers N and P. The P is the product of N unknown integers. We have to find the maximum possible GCD of those integers. 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.
We will find all prime factors of P, and store them into hashmap. The N integers will have max GCD when the prime factor will be common in all the integers. So if P = p1k1 * p2k2 * … * pnkn. Here pi is the prime factor. Then max GCD will be res = p1k1/N * p2k2/N * … * pnkn/N.
Example
#include <iostream> #include <cmath> #include <unordered_map> using namespace std; long getMaxGCD(long N, long p) { int gcd = 1; unordered_map<int, int> prime_factors; for (int i = 2; i * i <= p; i++) { while (p % i == 0) { prime_factors[i]++; p /= i; } } if (p != 1) prime_factors[p]++; for (auto v : prime_factors) gcd = gcd * pow(v.first, v.second / N); return gcd; } int main() { long n = 3; long p = 24; cout << "MAX GCD: " << getMaxGCD(n, p); }
Output
MAX GCD: 2
- Related Articles
- Maximum GCD from Given Product of Unknowns in C++
- Find N integers with given difference between product and sum in C++
- Find a pair with maximum product in array of Integers in C++
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- Recursive program to print formula for GCD of n integers in C++
- Maximum Product of Two Numbers in a List of Integers in JavaScript
- Subsequence of size k with maximum possible GCD
- Find four factors of N with maximum product and sum equal to N in C++
- C++ find four factors of N with maximum product and sum equal to N .
- Maximum number of ones in a N*N matrix with given constraints in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python
- Find four factors of N with maximum product and sum equal to N - Set-2 in C++
- Find pair with maximum GCD in an array in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python Program
- Maximum number of Unique integers in Sub- Array of given sizes in C++

Advertisements