📜  将给定阵列减少到其 LCM 所需的 LCM 对的最小替换

📅  最后修改于: 2021-09-05 08:34:56             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是从给定数组中找到最小数量的对(arr[i], arr[j])需要用它们的 LCM 替换,以便减少数组到等于初始数组的 LCM 的单个元素。
例子:

朴素的方法:这个想法是生成所有可能的对,对于每一对,用它们的LCM替换它们,并计算将它们减少到等于它们的 LCM 的单个数组元素所需的步骤数。打印所需的最少操作次数。
时间复杂度: O((N!)*log N)
辅助空间: O(N)

高效的方法:上述方法可以基于以下观察进行优化:

  • 数组的 LCM 等于数组中所有素数的乘积。
  • (X – 1)步中,所有X个素数的LCM可以用两个数成对得到。
  • 在接下来的(N – 2)步中,将其余(N – 2) 个元素转换为数组的 LCM。
  • 因此,总步数由下式给出:
  • 对于N = 1 ,操作次数为0 ,对于N = 2 ,操作次数为1

脚步:

  1. 如果 N = 1 则步数为0
  2. 如果 N = 2 则步数为1
  3. 使用 Sieve Of Eratosthenes 生成最多N 的所有素数。
  4. 将素数的数量存储在一个变量中,比如X
  5. 操作总数由下式给出:

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
const int maxm = 10001;
 
// Boolean array to set or unset
// prime non-prime indices
bool prime[maxm];
 
// Stores the prefix sum of the count
// of prime numbers
int prime_number[maxm];
 
// Function to check if a number
// is prime or not from 0 to N
void SieveOfEratosthenes()
{
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p < maxm; p++) {
 
        // If p is a prime
        if (prime[p] == true) {
 
            // Set its multiples as
            // non-prime
            for (int i = p * p; i < maxm;
                i += p)
                prime[i] = false;
        }
    }
 
    prime[0] = false;
    prime[1] = false;
}
 
// Function to store the count of
// prime numbers
void num_prime()
{
    prime_number[0] = 0;
 
    for (int i = 1; i <= maxm; i++)
 
        prime_number[i]
            = prime_number[i - 1]
            + prime[i];
}
 
// Function to count the operations
// to reduce the array to one element
// by replacing each pair with its LCM
void min_steps(int arr[], int n)
{
    // Generating Prime Number
    SieveOfEratosthenes();
 
    num_prime();
 
    // Corner Case
    if (n == 1)
        cout << "0\n";
 
    else if (n == 2)
        cout << "1\n";
 
    else
        cout << prime_number[n] - 1
                    + (n - 2);
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 5, 4, 3, 2, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    min_steps(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
     
static final int maxm = 10001;
 
// Boolean array to set or unset
// prime non-prime indices
static boolean prime[];
 
// Stores the prefix sum of the count
// of prime numbers
static int prime_number[];
 
// Function to check if a number
// is prime or not from 0 to N
static void SieveOfEratosthenes()
{
    Arrays.fill(prime,true);
 
    for(int p = 2; p * p < maxm; p++)
    {
         
        // If p is a prime
        if (prime[p] == true)
        {
             
            // Set its multiples as
            // non-prime
            for(int i = p * p; i < maxm; i += p)
                prime[i] = false;
        }
    }
    prime[0] = false;
    prime[1] = false;
}
 
// Function to store the count of
// prime numbers
static void num_prime()
{
    prime_number[0] = 0;
 
    for(int i = 1; i <= maxm; i++)
    {
        int tmp;
        if(prime[i] == true)
        {
            tmp = 1;
        }
        else
        {
            tmp = 0;
        }
        prime_number[i] = prime_number[i - 1] + tmp;
    }
}
 
// Function to count the operations
// to reduce the array to one element
// by replacing each pair with its LCM
static void min_steps(int arr[], int n)
{
     
    // Generating Prime Number
    SieveOfEratosthenes();
 
    num_prime();
 
    // Corner Case
    if (n == 1)
    {
        System.out.println("0");
    }
    else if (n == 2)
    {
        System.out.println("1");
    }
    else
    {
        System.out.println(prime_number[n] - 1 +
                                        (n - 2));
    }
}
 
// Driver code   
public static void main(String[] args)
{
    prime = new boolean[maxm + 1];
     
    // Stores the prefix sum of the count
    // of prime numbers
    prime_number = new int[maxm + 1];
     
    // Given array arr[]
    int arr[] = { 5, 4, 3, 2, 1 };
    int N = arr.length;
     
    // Function call
    min_steps(arr, N);
}
}
 
// This code is contributed by rutvik_56


Python3
# Python3 program for
# the above approach
maxm = 10001;
 
# Boolean array to set or unset
# prime non-prime indices
prime = [True] * (maxm + 1);
 
# Stores the prefix sum of the count
# of prime numbers
prime_number = [0] * (maxm + 1);
 
# Function to check if a number
# is prime or not from 0 to N
def SieveOfEratosthenes():
 
    for p in range(2, (int(maxm ** 1 / 2))):
 
        # If p is a prime
        if (prime[p] == True):
 
            # Set its multiples as
            # non-prime
            for i in range(p * p, maxm, p):
                prime[i] = False;
 
    prime[0] = False;
    prime[1] = False;
 
# Function to store the count of
# prime numbers
def num_prime():
    prime_number[0] = 0;
 
    for i in range(1, maxm + 1):
        tmp = -1;
        if (prime[i] == True):
            tmp = 1;
        else:
            tmp = 0;
 
        prime_number[i] = prime_number[i - 1] + tmp;
 
 
# Function to count the operations
# to reduce the array to one element
# by replacing each pair with its LCM
def min_steps(arr, n):
   
    # Generating Prime Number
    SieveOfEratosthenes();
 
    num_prime();
 
    # Corner Case
    if (n == 1):
        print("0");
    elif (n == 2):
        print("1");
    else:
        print(prime_number[n] - 1 + (n - 2));
 
# Driver code
if __name__ == '__main__':
   
    # Given array arr
    arr = [5, 4, 3, 2, 1];
    N = len(arr);
 
    # Function call
    min_steps(arr, N);
 
# This code is contributed by Rajput-Ji


C#
// C# program for the above approach
using System;
class GFG{
     
static readonly int maxm = 10001;
 
// Boolean array to set or unset
// prime non-prime indices
static bool []prime;
 
// Stores the prefix sum of the count
// of prime numbers
static int []prime_number;
 
// Function to check if a number
// is prime or not from 0 to N
static void SieveOfEratosthenes()
{
    for(int i = 0; i < prime.Length; i++)
        prime[i] = true;
    for(int p = 2; p * p < maxm; p++)
    {       
        // If p is a prime
        if (prime[p] == true)
        {           
            // Set its multiples as
            // non-prime
            for(int i = p * p; i < maxm;
                i += p)
                prime[i] = false;
        }
    }
    prime[0] = false;
    prime[1] = false;
}
 
// Function to store the count of
// prime numbers
static void num_prime()
{
    prime_number[0] = 0;
 
    for(int i = 1; i <= maxm; i++)
    {
        int tmp;
        if(prime[i] == true)
        {
            tmp = 1;
        }
        else
        {
            tmp = 0;
        }
        prime_number[i] = prime_number[i - 1] +
                          tmp;
    }
}
 
// Function to count the operations
// to reduce the array to one element
// by replacing each pair with its LCM
static void min_steps(int []arr, int n)
{   
    // Generating Prime Number
    SieveOfEratosthenes();
 
    num_prime();
 
    // Corner Case
    if (n == 1)
    {
        Console.WriteLine("0");
    }
    else if (n == 2)
    {
        Console.WriteLine("1");
    }
    else
    {
        Console.WriteLine(prime_number[n] - 1 +
                          (n - 2));
    }
}
 
// Driver code   
public static void Main(String[] args)
{
    prime = new bool[maxm + 1];
     
    // Stores the prefix sum of the count
    // of prime numbers
    prime_number = new int[maxm + 1];
     
    // Given array []arr
    int []arr = {5, 4, 3, 2, 1};
    int N = arr.Length;
     
    // Function call
    min_steps(arr, N);
}
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:
5

时间复杂度: O(N + log(log(maxm))
辅助空间: O(maxm)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live