📌  相关文章
📜  查找一个将最大数组元素相除的数字

📅  最后修改于: 2021-04-24 04:37:14             🧑  作者: Mango

给定一个由N个非负整数组成的数组A []。查找一个大于1的整数,这样最大的数组元素就可以被整数整除。如果答案相同,则打印较小的答案。

例子

天真的方法:运行一个for循环,直到数组的最大元素。设为K。迭代数组并将数组的每个元素除以所有数字1 \leq i \leq K 。根据获得的最大元素数除以元素i来更新结果。

高效的方法:我们知道,数字只能由可以由其主要因子形成的元素整除。
因此,我们找到了数组所有元素的素因,并将它们的频率存储在哈希中。最后,我们返回其中具有最大频率的元素。

您可以使用factorization-using-sieve在Log(n)中找到主要因子。

下面是上述方法的实现:

C++
// CPP program to find a number that
// divides maximum array elements
  
#include 
using namespace std;
  
#define MAXN 100001
  
// stores smallest prime factor for every number
int spf[MAXN];
  
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
void sieve()
{
    spf[1] = 1;
    for (int i = 2; i < MAXN; i++)
  
        // marking smallest prime factor for every
        // number to be itself.
        spf[i] = i;
  
    // separately marking spf for every even
    // number as 2
    for (int i = 4; i < MAXN; i += 2)
        spf[i] = 2;
  
    for (int i = 3; i * i < MAXN; i++) {
        // checking if i is prime
        if (spf[i] == i) {
            // marking SPF for all numbers divisible by i
            for (int j = i * i; j < MAXN; j += i)
  
                // marking spf[j] if it is not
                // previously marked
                if (spf[j] == j)
                    spf[j] = i;
        }
    }
}
  
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
vector getFactorization(int x)
{
    vector ret;
    while (x != 1) {
        int temp = spf[x];
        ret.push_back(temp);
        while (x % temp == 0)
            x = x / temp;
    }
    return ret;
}
  
// Function to find a number that
// divides maximum array elements
int maxElement(int A[], int n)
{
    // precalculating Smallest Prime Factor
    sieve();
  
    // Hash to store frequency of each divisors
    map m;
  
    // Traverse the array and get spf of each element
    for (int i = 0; i < n; ++i) {
  
        // calling getFactorization function
        vector p = getFactorization(A[i]);
  
        for (int i = 0; i < p.size(); i++)
            m[p[i]]++;
    }
  
    int cnt = 0, ans = 1e+7;
  
    for (auto i : m) {
        if (i.second >= cnt) {
            cnt = i.second;
            ans > i.first ? ans = i.first : ans = ans;
        }
    }
  
    return ans;
}
  
// Driver program
int main()
{
    int A[] = { 2, 5, 10 };
    int n = sizeof(A) / sizeof(A[0]);
  
    cout << maxElement(A, n);
  
    return 0;
}


Java
// Java program to find a number that 
// divides maximum array elements 
import java.util.*;
class Solution
{
static final int MAXN=100001; 
    
// stores smallest prime factor for every number 
static int spf[]= new int[MAXN]; 
    
// Calculating SPF (Smallest Prime Factor) for every 
// number till MAXN. 
// Time Complexity : O(nloglogn) 
static void sieve() 
{ 
    spf[1] = 1; 
    for (int i = 2; i < MAXN; i++) 
    
        // marking smallest prime factor for every 
        // number to be itself. 
        spf[i] = i; 
    
    // separately marking spf for every even 
    // number as 2 
    for (int i = 4; i < MAXN; i += 2) 
        spf[i] = 2; 
    
    for (int i = 3; i * i < MAXN; i++) { 
        // checking if i is prime 
        if (spf[i] == i) { 
            // marking SPF for all numbers divisible by i 
            for (int j = i * i; j < MAXN; j += i) 
    
                // marking spf[j] if it is not 
                // previously marked 
                if (spf[j] == j) 
                    spf[j] = i; 
        } 
    } 
} 
    
// A O(log n) function returning primefactorization 
// by dividing by smallest prime factor at every step 
static Vector getFactorization(int x) 
{ 
    Vector ret= new Vector(); 
    while (x != 1) { 
        int temp = spf[x]; 
        ret.add(temp); 
        while (x % temp == 0) 
            x = x / temp; 
    } 
    return ret; 
} 
    
// Function to find a number that 
// divides maximum array elements 
static int maxElement(int A[], int n) 
{ 
    // precalculating Smallest Prime Factor 
    sieve(); 
    
    // Hash to store frequency of each divisors 
    Map m= new HashMap(); 
    
    // Traverse the array and get spf of each element 
    for (int j = 0; j < n; ++j) { 
    
        // calling getFactorization function 
        Vector p = getFactorization(A[j]); 
    
        for (int i = 0; i < p.size(); i++) 
            m.put(p.get(i),m.get(p.get(i))==null?0:m.get(p.get(i))+1); 
    } 
    
    int cnt = 0, ans = 10000000; 
    // Returns Set view      
       Set< Map.Entry< Integer,Integer> > st = m.entrySet();    
    
       for (Map.Entry< Integer,Integer> me:st) 
       { 
        if (me.getValue() >= cnt) { 
            cnt = me.getValue(); 
            if(ans > me.getKey()) 
            ans = me.getKey() ;
            else
            ans = ans; 
        } 
    } 
    
    return ans; 
} 
    
// Driver program 
public static void main(String args[])
{ 
    int A[] = { 2, 5, 10 }; 
    int n =A.length; 
    
    System.out.print(maxElement(A, n)); 
    
  
} 
}
//contributed by Arnab Kundu


Python3
# Python3 program to find a number that 
# divides maximum array elements
import math as mt
  
MAXN = 100001
  
# stores smallest prime factor for 
# every number
spf = [0 for i in range(MAXN)]
  
# Calculating SPF (Smallest Prime Factor) 
# for every number till MAXN.
# Time Complexity : O(nloglogn)
def sieve():
  
    spf[1] = 1
    for i in range(2, MAXN):
  
        # marking smallest prime factor for 
        # every number to be itself.
        spf[i] = i
  
    # separately marking spf for every 
    # even number as 2
    for i in range(4, MAXN, 2):
        spf[i] = 2
  
    for i in range(3, mt.ceil(mt.sqrt(MAXN + 1))):
          
        # checking if i is prime
        if (spf[i] == i): 
              
            # marking SPF for all numbers divisible by i
            for j in range(2 * i, MAXN, i):
  
                # marking spf[j] if it is not
                # previously marked
                if (spf[j] == j):
                    spf[j] = i
          
# A O(log n) function returning primefactorization
# by dividing by smallest prime factor at every step
def getFactorization (x):
  
    ret = list()
    while (x != 1): 
        temp = spf[x]
        ret.append(temp)
        while (x % temp == 0):
            x = x //temp
      
    return ret
  
# Function to find a number that
# divides maximum array elements
def maxElement (A, n):
  
    # precalculating Smallest Prime Factor
    sieve()
  
    # Hash to store frequency of each divisors
    m = dict()
  
    # Traverse the array and get spf of each element
    for i in range(n): 
  
        # calling getFactorization function
        p = getFactorization(A[i])
  
        for i in range(len(p)):
            if p[i] in m.keys():
                m[p[i]] += 1
            else:
                m[p[i]] = 1
  
    cnt = 0
    ans = 10**9+7
  
    for i in m: 
        if (m[i] >= cnt):
            cnt = m[i]
            if ans > i:
                ans = i
            else:
                ans = ans
  
    return ans
  
# Driver Code
A = [2, 5, 10 ]
n = len(A)
  
print(maxElement(A, n))
  
# This code is contributed by Mohit kumar 29


C#
// C# program to find a number that 
// divides maximum array elements 
using System;
using System.Collections.Generic;
  
class Solution
{
      
static readonly int MAXN = 100001; 
      
// stores smallest prime factor for every number 
static int []spf = new int[MAXN]; 
      
// Calculating SPF (Smallest Prime Factor) for every 
// number till MAXN. 
// Time Complexity : O(nloglogn) 
static void sieve() 
{ 
    spf[1] = 1; 
    for (int i = 2; i < MAXN; i++) 
      
        // marking smallest prime factor for every 
        // number to be itself. 
        spf[i] = i; 
      
    // separately marking spf for every even 
    // number as 2 
    for (int i = 4; i < MAXN; i += 2) 
        spf[i] = 2; 
      
    for (int i = 3; i * i < MAXN; i++) 
    { 
        // checking if i is prime 
        if (spf[i] == i) 
        { 
            // marking SPF for all numbers divisible by i 
            for (int j = i * i; j < MAXN; j += i) 
      
                // marking spf[j] if it is not 
                // previously marked 
                if (spf[j] == j) 
                    spf[j] = i; 
        } 
    } 
} 
      
// A O(log n) function returning primefactorization 
// by dividing by smallest prime factor at every step 
static List getFactorization(int x) 
{ 
    List ret= new List(); 
    while (x != 1)
    { 
        int temp = spf[x]; 
        ret.Add(temp); 
        while (x % temp == 0) 
            x = x / temp; 
    } 
    return ret; 
} 
      
// Function to find a number that 
// divides maximum array elements 
static int maxElement(int []A, int n) 
{ 
    // precalculating Smallest Prime Factor 
    sieve(); 
      
    // Hash to store frequency of each divisors 
    Dictionary m= new Dictionary(); 
      
    // Traverse the array and get spf of each element 
    for (int j = 0; j < n; ++j) 
    { 
      
        // calling getFactorization function 
        List p = getFactorization(A[j]); 
      
        for (int i = 0; i < p.Count; i++) 
            if(m.ContainsKey(p[i]))
            m[p[i]] = m[p[i]] + 1; 
            else
                m.Add(p[i], 1); 
    } 
      
    int cnt = 0, ans = 10000000; 
      
    // Returns Set view     
    foreach(KeyValuePair me in m) 
    { 
        if (me.Value >= cnt)
        { 
            cnt = me.Value; 
            if(ans > me.Key) 
                ans = me.Key ;
            else
                ans = ans; 
        } 
    } 
      
    return ans; 
} 
      
// Driver program 
public static void Main(String []args)
{ 
    int []A = { 2, 5, 10 }; 
    int n =A.Length; 
      
    Console.Write(maxElement(A, n)); 
} 
}
  
// This code is contributed by 29AjayKumar


输出:
2

时间复杂度: O(N * log(N))