📜  GCD大于1的最大子序列

📅  最后修改于: 2021-04-30 02:38:51             🧑  作者: Mango

给定一个数组arr [],找到最大的子序列,使得所有这些子序列中的GCD都大于1。
例子:

Input: 3, 6, 2, 5, 4
Output: 3
Explanation: There are only three elements(6, 
2, 4) having GCD greater than 1 i.e., 2. So the 
largest subsequence will be 3

Input: 10, 15, 7, 25, 9, 35
Output: 4

天真的方法(方法1)

一种简单的方法是一一生成所有子序列,然后找到所有此类生成集的GCD。这种方法的问题是它在2 N中呈指数增长

迭代法(方法2)

如果观察的话,我们将发现要使gcd大于1,所有这些元素必须包含大于1的命令因子,该命令将所有这些值均分。因此,为了得到该因子,我们将从2迭代到array的Maximum元素,然后检查可除性。

C++
// Simple C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include
 
using namespace std;
 
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
 
    // Finding the Maximum value in arr[]
    int maxele = *max_element(arr, arr+n);
 
    // Iterate from 2 to maximum possible
    // divisor of all give values
    for (int i=2; i<=maxele; ++i)
    {
        int count = 0;
        for (int j=0; j


Java
// Efficient Java program to find length of
// the largest subsequence with GCD greater
// than 1.
import java.util.Arrays;
 
class GFG {
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
  
    // Finding the Maximum value in arr[]
    int maxele = Arrays.stream(arr).max().getAsInt();;
  
    // Iterate from 2 to maximum possible
    // divisor of all give values
    for (int i=2; i<=maxele; ++i)
    {
        int count = 0;
        for (int j=0; j


Python3
# Simple Python 3 program to find length of
# the largest subsequence with GCD greater
# than 1.
 
# Returns length of the largest subsequence
# with GCD more than 1.
def largestGCDSubsequence(arr, n):
    ans = 0
 
    # Finding the Maximum value in arr[]
    maxele = max(arr)
 
    # Iterate from 2 to maximum possible
    # divisor of all give values
    for i in range(2, maxele + 1):
        count = 0
        for j in range(n):
             
            # If we found divisor,
            # increment count
            if (arr[j] % i == 0):
                count += 1
        ans = max(ans, count)
 
    return ans
 
# Driver code
if __name__ == '__main__':
    arr = [3, 6, 2, 5, 4]
    size = len(arr)
    print(largestGCDSubsequence(arr, size))
 
# This code is contributed by Rajput-Ji


C#
// Efficient C# program to find length of
// the largest subsequence with GCD greater
// than 1.
using System;
using System.Linq;
public class GFG {
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int []arr, int n)
{
    int ans = 0;
   
    // Finding the Maximum value in arr[]
    int maxele = arr.Max();
   
    // Iterate from 2 to maximum possible
    // divisor of all give values
    for (int i=2; i<=maxele; ++i)
    {
        int count = 0;
        for (int j=0; j


PHP


Javascript


C++
// Efficient C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include
 
using namespace std;
 
#define MAX 100001
 
// prime[] for storing smallest prime divisor of element
// count[] for storing the number of times a particular
// divisor occurs in a subsequence
int prime[MAX], countdiv[MAX];
 
// Simple sieve to find smallest prime factors of numbers
// smaller than MAX
void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (!prime[i])
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (!prime[i])
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
    for (int i=0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = max(ans, countdiv[div]);
 
            while (element % div==0)
                element /= div;
        }
    }
 
    return ans;
}
 
// Driver code
int main()
{
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    int arr[] = {10, 15, 7, 25, 9, 35};
    int size = sizeof(arr) / sizeof(arr[0]);
 
    cout << largestGCDSubsequence(arr, size);
    return 0;
}


Java
// Efficient Java program to find length of
// the largest subsequence with GCD greater
// than 1.
 
class GFG
{
static int MAX = 100001;
 
// prime[] for storing smallest prime divisor
// of element count[] for storing the number
// of times a particular divisor occurs
// in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
 
// Simple sieve to find smallest prime
// factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (prime[i] == 0)
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (prime[i] == 0)
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
    for (int i = 0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = Math.max(ans, countdiv[div]);
 
            while (element % div == 0)
                element /= div;
        }
    }
    return ans;
}
 
// Driver code
public static void main (String[] args)
{
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    int arr[] = {10, 15, 7, 25, 9, 35};
    int size = arr.length;
 
    System.out.println(largestGCDSubsequence(arr, size));
}
}
 
// This code is contributed by mits


Python3
# Efficient Python3 program to find length
# of the largest subsequence with GCD
# greater than 1.
import math as mt
 
MAX = 100001
 
# prime[] for storing smallest
# prime divisor of element
# count[] for storing the number
# of times a particular divisor
# occurs in a subsequence
prime = [0 for i in range(MAX + 1)]
countdiv = [0 for i in range(MAX + 1)]
 
# Simple sieve to find smallest prime
# factors of numbers smaller than MAX
def SieveOfEratosthenes():
 
    for i in range(2, mt.ceil(mt.sqrt(MAX + 1))):
     
        if (prime[i] == 0):
            for j in range(i * 2, MAX + 1, i):
                prime[j] = i
     
    # Prime number will have same divisor
    for i in range(1, MAX):
        if (prime[i] == 0):
            prime[i] = i
 
# Returns length of the largest
# subsequence with GCD more than 1.
def largestGCDSubsequence(arr, n):
 
    ans = 0
    for i in range(n):
 
        element = arr[i]
 
        # Fetch total unique prime
        # divisor of element
        while (element > 1):
 
            div = prime[element]
 
            # Increment count[] of Every
            # unique divisor we get till now
            countdiv[div] += 1
 
            # Find maximum frequency of divisor
            ans = max(ans, countdiv[div])
 
            while (element % div == 0):
                element = element // div
         
    return ans
 
# Driver code
 
# Pre-compute smallest divisor
# of all numbers
SieveOfEratosthenes()
 
arr= [10, 15, 7, 25, 9, 35]
size = len(arr)
print(largestGCDSubsequence(arr, size))
 
# This code is contributed
# by Mohit kumar 29


C#
// Efficient C# program to find length of
// the largest subsequence with GCD greater
// than 1.
using System;
 
class GFG
{
     
static int MAX=100001;
 
// prime[] for storing smallest
// prime divisor of element count[]
// for storing the number of times
// a particular divisor occurs in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
 
// Simple sieve to find smallest prime
//  factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (prime[i] == 0)
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (prime[i] == 0)
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int []arr, int n)
{
    int ans = 0;
    for (int i = 0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = Math.Max(ans, countdiv[div]);
 
            while (element % div==0)
                element /= div;
        }
    }
    return ans;
}
 
// Driver code
public static void Main()
{
    // Pre-compute smallest
    // divisor of all numbers
    SieveOfEratosthenes();
 
    int []arr = {10, 15, 7, 25, 9, 35};
    int size = arr.Length;
 
    Console.WriteLine(largestGCDSubsequence(arr, size));
}
}
 
// This code is contributed by mits


PHP
 1)
        {
            $div = $prime[$element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++$countdiv[$div];
 
            // Find maximum frequency of divisor
            $ans = max($ans, $countdiv[$div]);
 
            while ($element % $div == 0)
                $element = (int)($element/$div);
        }
    }
 
    return $ans;
}
 
    // Driver code
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    $arr = array(10, 15, 7, 25, 9, 35);
    $size = count($arr);
 
    echo largestGCDSubsequence($arr, $size);
 
// This code is contributed by mits
?>


输出:

3

时间复杂度: O(n * max(arr [i])),其中n是数组的大小。
辅助空间: O(1)

最佳方法(方法3)

一种有效的方法是在Eratosthenes的Sieve的帮助下使用素数分解方法。首先,我们将通过预先计算的筛子找到所有元素中最小的素数除数。之后,我们将借助预先计算的prime []数组将其归因于arr []的每个元素的所有质数除数。
现在,我们在所有数组元素中都出现了所有标记的素数。最后一步是找到所有这些主要因素的最大数量。

C++

// Efficient C++ program to find length of
// the largest subsequence with GCD greater
// than 1.
#include
 
using namespace std;
 
#define MAX 100001
 
// prime[] for storing smallest prime divisor of element
// count[] for storing the number of times a particular
// divisor occurs in a subsequence
int prime[MAX], countdiv[MAX];
 
// Simple sieve to find smallest prime factors of numbers
// smaller than MAX
void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (!prime[i])
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (!prime[i])
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
    for (int i=0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = max(ans, countdiv[div]);
 
            while (element % div==0)
                element /= div;
        }
    }
 
    return ans;
}
 
// Driver code
int main()
{
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    int arr[] = {10, 15, 7, 25, 9, 35};
    int size = sizeof(arr) / sizeof(arr[0]);
 
    cout << largestGCDSubsequence(arr, size);
    return 0;
}

Java

// Efficient Java program to find length of
// the largest subsequence with GCD greater
// than 1.
 
class GFG
{
static int MAX = 100001;
 
// prime[] for storing smallest prime divisor
// of element count[] for storing the number
// of times a particular divisor occurs
// in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
 
// Simple sieve to find smallest prime
// factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (prime[i] == 0)
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (prime[i] == 0)
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int arr[], int n)
{
    int ans = 0;
    for (int i = 0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = Math.max(ans, countdiv[div]);
 
            while (element % div == 0)
                element /= div;
        }
    }
    return ans;
}
 
// Driver code
public static void main (String[] args)
{
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    int arr[] = {10, 15, 7, 25, 9, 35};
    int size = arr.length;
 
    System.out.println(largestGCDSubsequence(arr, size));
}
}
 
// This code is contributed by mits

Python3

# Efficient Python3 program to find length
# of the largest subsequence with GCD
# greater than 1.
import math as mt
 
MAX = 100001
 
# prime[] for storing smallest
# prime divisor of element
# count[] for storing the number
# of times a particular divisor
# occurs in a subsequence
prime = [0 for i in range(MAX + 1)]
countdiv = [0 for i in range(MAX + 1)]
 
# Simple sieve to find smallest prime
# factors of numbers smaller than MAX
def SieveOfEratosthenes():
 
    for i in range(2, mt.ceil(mt.sqrt(MAX + 1))):
     
        if (prime[i] == 0):
            for j in range(i * 2, MAX + 1, i):
                prime[j] = i
     
    # Prime number will have same divisor
    for i in range(1, MAX):
        if (prime[i] == 0):
            prime[i] = i
 
# Returns length of the largest
# subsequence with GCD more than 1.
def largestGCDSubsequence(arr, n):
 
    ans = 0
    for i in range(n):
 
        element = arr[i]
 
        # Fetch total unique prime
        # divisor of element
        while (element > 1):
 
            div = prime[element]
 
            # Increment count[] of Every
            # unique divisor we get till now
            countdiv[div] += 1
 
            # Find maximum frequency of divisor
            ans = max(ans, countdiv[div])
 
            while (element % div == 0):
                element = element // div
         
    return ans
 
# Driver code
 
# Pre-compute smallest divisor
# of all numbers
SieveOfEratosthenes()
 
arr= [10, 15, 7, 25, 9, 35]
size = len(arr)
print(largestGCDSubsequence(arr, size))
 
# This code is contributed
# by Mohit kumar 29

C#

// Efficient C# program to find length of
// the largest subsequence with GCD greater
// than 1.
using System;
 
class GFG
{
     
static int MAX=100001;
 
// prime[] for storing smallest
// prime divisor of element count[]
// for storing the number of times
// a particular divisor occurs in a subsequence
static int[] prime = new int[MAX + 1];
static int[] countdiv = new int[MAX + 1];
 
// Simple sieve to find smallest prime
//  factors of numbers smaller than MAX
static void SieveOfEratosthenes()
{
    for (int i = 2; i * i <= MAX; ++i)
    {
        if (prime[i] == 0)
            for (int j = i * 2; j <= MAX; j += i)
                prime[j] = i;
    }
 
    // Prime number will have same divisor
    for (int i = 1; i < MAX; ++i)
        if (prime[i] == 0)
            prime[i] = i;
}
 
// Returns length of the largest subsequence
// with GCD more than 1.
static int largestGCDSubsequence(int []arr, int n)
{
    int ans = 0;
    for (int i = 0; i < n; ++i)
    {
        int element = arr[i];
 
        // Fetch total unique prime divisor of element
        while (element > 1)
        {
            int div = prime[element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++countdiv[div];
 
            // Find maximum frequency of divisor
            ans = Math.Max(ans, countdiv[div]);
 
            while (element % div==0)
                element /= div;
        }
    }
    return ans;
}
 
// Driver code
public static void Main()
{
    // Pre-compute smallest
    // divisor of all numbers
    SieveOfEratosthenes();
 
    int []arr = {10, 15, 7, 25, 9, 35};
    int size = arr.Length;
 
    Console.WriteLine(largestGCDSubsequence(arr, size));
}
}
 
// This code is contributed by mits

的PHP

 1)
        {
            $div = $prime[$element];
 
            // Increment count[] of Every unique divisor
            // we get till now
            ++$countdiv[$div];
 
            // Find maximum frequency of divisor
            $ans = max($ans, $countdiv[$div]);
 
            while ($element % $div == 0)
                $element = (int)($element/$div);
        }
    }
 
    return $ans;
}
 
    // Driver code
    // Pre-compute smallest divisor of all numbers
    SieveOfEratosthenes();
 
    $arr = array(10, 15, 7, 25, 9, 35);
    $size = count($arr);
 
    echo largestGCDSubsequence($arr, $size);
 
// This code is contributed by mits
?>

输出:

4