📜  用其LCM最小替换对,以减少给定阵列到其LCM所需的空间

📅  最后修改于: 2021-05-17 21:12:09             🧑  作者: Mango

给定一个由N个正整数组成的数组arr [] ,任务是从给定数组中查找需要用其LCM替换的最小对数(arr [i],arr [j]) ,从而减少该数组等于与初始数组的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. 使用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)