给定n个整数,我们需要找到GCD等于1的最大子集的大小。
输入约束:
n <= 10^5
A[i] <= 10^5
例子:
Input : A = {2, 3, 5}
Output : 3
Input : A = {3, 18, 12}
Output : -1
天真的解决方案:
我们找到所有可能的子集的GCD,并找到GCD为1的最大子集。总花费的时间将等于评估所有可能的子集的GCD所花费的时间。可能的子集总数为2 n 。最坏的情况是子集中有n个元素,计算其GCD所需的时间为n * log(n)
容纳当前子集所需的额外空间为O(n)
Time complexity : O(n * log(n) * 2^n)
Space Complexity : O(n)
优化的O(n)解决方案:
假设我们找到了一个GCD 1的子集,如果我们向它添加一个新元素,那么GCD仍然保持1。因此,如果一个子集的GCD 1存在,那么整个集合的GCD也是1。因此,我们首先找到完整的GCD集合,如果它的1,则完整集合是该子集,否则GCD 1不存在任何子集。
C++
// C++ program to find size of the largest subset with GCD 1
#include
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
// Function to find largest subset with GCD 1
int largestGCD1Subset(int A[], int n)
{
// finding gcd of whole array
int currentGCD = A[0];
for (int i=1; i
Java
// Java program to find size of the
// largest subset with GCD 1
import java.*;
class GFG {
// Function to return gcd of
// a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to find largest
// subset with GCD 1
static int largestGCD1Subset(int A[],
int n)
{
// finding gcd of whole array
int currentGCD = A[0];
for (int i=1; i
Python3
# python program to find size of the
# largest subset with GCD 1
# Function to return gcd of a and b
def gcd( a, b):
if (a == 0):
return b
return gcd(b%a, a)
# Function to find largest subset
# with GCD 1
def largestGCD1Subset(A, n):
# finding gcd of whole array
currentGCD = A[0];
for i in range(1, n):
currentGCD = gcd(currentGCD, A[i])
# If current GCD becomes 1 at
# any momemnt, then whole
# array has GCD 1.
if (currentGCD == 1):
return n
return 0
# Driver code
A = [2, 18, 6, 3]
n = len(A)
print (largestGCD1Subset(A, n))
# This code is Contributed by Sam007.
C#
// C# program to find size of the
// largest subset with GCD 1
using System;
public class GFG {
// Function to return gcd of
// a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to find largest subset
// with GCD 1
static int largestGCD1Subset(int []A,
int n)
{
// finding gcd of whole array
int currentGCD = A[0];
for (int i = 1; i < n; i++)
{
currentGCD =
gcd(currentGCD, A[i]);
// If current GCD becomes 1 at
// any momemnt, then whole
// array has GCD 1.
if (currentGCD == 1)
return n;
}
return 0;
}
// Driver method
public static void Main()
{
int []A = {2, 18, 6, 3};
int n = A.Length;
Console.Write(
largestGCD1Subset(A, n));
}
}
// This code is contributed by Sam007.
PHP
Javascript
输出:
4
Time Complexity : O(n* log(n))
Space Complexity : O(1)