이 문제에서는 n개의 정수로 구성된 배열 arr[]가 제공됩니다.
우리의 임무는 배열 요소의 최대 수를 나누는 정수를 찾는 것입니다.
문제 설명: 배열의 최대 요소 수를 나눌 수 있는 숫자 p를 찾아야 합니다. 그러한 요소가 둘 이상인 경우 더 작은 요소를 반환합니다.
문제를 이해하기 위해 예를 들어 보겠습니다.
입력: arr[] ={4, 5, 6, 7, 8}
출력: 2
설명:
요소 2는 {4, 6, 8}을 나눕니다.
솔루션 접근 방식
문제에 대한 간단한 해결책은 배열을 반복한 다음 배열의 각 요소에 대해 배열의 각 요소를 1에서 k까지의 요소로 나누는 것입니다. 그리고 배열의 요소의 최대 개수를 나눈 요소를 반환합니다.
또 다른 접근 방식 문제를 해결하는 방법은 배열의 모든 요소를 소인수로 나눈다는 사실을 사용하는 것입니다.
각 소수로 나눈 빈도를 저장한 다음 최대 빈도로 인수를 반환합니다. 소수와 빈도를 해시에 저장합니다.
우리 솔루션의 작동을 설명하는 프로그램,
예시
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100001
int primes[MAXN];
void findPrimeSieve()
{
primes[1] = 1;
for (int i = 2; i < MAXN; i++)
primes[i] = i;
for (int i = 4; i < MAXN; i += 2)
primes[i] = 2;
for (int i = 3; i * i < MAXN; i++) {
if (primes[i] == i) {
for (int j = i * i; j < MAXN; j += i)
if (primes[j] == j)
primes[j] = i;
}
}
}
vector<int> findFactors(int num)
{
vector<int> factors;
while (num != 1) {
int temp = primes[num];
factors.push_back(temp);
while (num % temp == 0)
num = num / temp;
}
return factors;
}
int findmaxDivElement(int arr[], int n) {
findPrimeSieve();
map<int, int> factorFreq;
for (int i = 0; i < n; ++i) {
vector<int> p = findFactors(arr[i]);
for (int i = 0; i < p.size(); i++)
factorFreq[p[i]]++;
}
int cnt = 0, ans = 1e+7;
for (auto itr : factorFreq) {
if (itr.second >= cnt) {
cnt = itr.second;
ans > itr.first ? ans = itr.first : ans = ans;
}
}
return ans;
}
int main() {
int arr[] = { 4, 5, 6, 7, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The number that divides the maximum elements of the array is "<<findmaxDivElement(arr, n);
return 0;
} 출력
The number that divides the maximum elements of the array is 2