📌  相关文章
📜  通过左移位数最小次数最大程度地增加素数和非素数数组元素之和之间的差

📅  最后修改于: 2021-04-17 18:28:17             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是通过将数组元素的位数左移1个最小值,来找到素数和与非素数和之间的最大差。次数。  

例子:

方法:可以贪婪地解决给定的问题。如果有可能将一个元素转换为一个或多个一个质数,则取它们中的最大值。否则,请尝试使用所有可能的旋转来最小化元素。
请按照以下步骤解决问题:

  • 初始化两个变量,分别为anscost,以分别存储所需的最大差异和最小操作数。
  • 使用变量i遍历数组arr []并执行以下步骤:
    • 将变量maxPrimeminRotation初始化为-1,以存储通过左旋转从arr [i]获得的最大素数和最小素数。
    • 生成数字arr [i]的所有向左旋转。
      • 如果arr [i]是超过maxPrime的素数,则将maxPrime更新为arr [i],并相应地更新成本
    • 如果maxPrime的值保持不变,通过类似地生成所有左旋转来找到minRotation的值。
    • arr [i]的值添加到ans
  • 完成上述步骤后,打印出ans值和成本作为结果。

下面是上述方法的实现:

C++14
// C++ program for the above approach
#include 
using namespace std;
 
// Fuction to check if a
// number is prime or not
bool isPrime(int n)
{
 
    // Base cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
 
    // Check if the number is
    // a multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    int i = 5;
 
    // Iterate until square root of n
    while (i * i <= n) {
 
        // If n is divisible by both i and i + 2
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
        i = i + 6;
    }
    return true;
}
 
// Function to left shift a number
// to maximize its contribution
pair rotateElement(int n)
{
 
    // Convert the number to string
    string strN = to_string(n);
 
    // Stores the maximum prime number
    // that can be obtained from n
    int maxPrime = -1;
 
    // Store the required
    // number of operations
    int cost = 0;
 
    string temp = strN;
 
    // Check for all the left
    // rotations of the number
    for (int i = 0; i < strN.size(); i++) {
 
        // If the number is prime, then
        // take the maximum among them
        if (isPrime(stoi(temp)) && stoi(temp) > maxPrime) {
            maxPrime = stoi(temp);
            cost = i;
        }
 
        // Left rotation
        temp = temp.substr(1) + temp[0];
    }
 
    int optEle = maxPrime;
 
    // If no prime number can be obtained
    if (optEle == -1) {
        optEle = INT_MAX;
        temp = strN;
 
        // Check all the left
        // rotations of the number
        for (int i = 0; i < strN.size(); i++) {
 
            // Take the minimum element
            if (stoi(temp) < optEle) {
                optEle = stoi(temp);
                cost = i;
            }
 
            // Left rotation
            temp = temp.substr(1) + temp[0];
        }
        optEle *= (-1);
    }
 
    return { optEle, cost };
}
 
// Function to find the maximum sum
// obtained using the given operations
void getMaxSum(int arr[], int N)
{
 
    // Store the maximum sum and
    // the number of operations
    int maxSum = 0, cost = 0;
 
    // Traverse array elements
    for (int i = 0; i < N; i++) {
        int x = arr[i];
 
        // Get the optimal element and the
        // number of operations to obtain it
        pair ret = rotateElement(x);
 
        int optEle = ret.first, optCost = ret.second;
 
        // Increment the maximum difference
        // and number of operations required
        maxSum += optEle;
        cost += optCost;
    }
 
    // Print the result
    cout << "Difference = " << maxSum << " , "
         << "Count of operations = " << cost;
}
 
// Driven Program
int main()
{
    // Given array arr[]
    int arr[] = { 541, 763, 321, 716, 143 };
 
    // Store the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    getMaxSum(arr, N);
 
    return 0;
}


Java
// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Fuction to check if a
    // number is prime or not
    static boolean isPrime(int n)
    {
 
        // Base cases
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
 
        // Check if the number is
        // a multiple of 2 or 3
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        int i = 5;
 
        // Iterate until square root of n
        while (i * i <= n) {
 
            // If n is divisible by both i and i + 2
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
            i = i + 6;
        }
        return true;
    }
 
    // Function to left shift a number
    // to maximize its contribution
    static int[] rotateElement(int n)
    {
 
        // Convert the number to string
        String strN = Integer.toString(n);
 
        // Stores the maximum prime number
        // that can be obtained from n
        int maxPrime = -1;
 
        // Store the required
        // number of operations
        int cost = 0;
 
        String temp = strN;
 
        // Check for all the left
        // rotations of the number
        for (int i = 0; i < strN.length(); i++) {
 
            // If the number is prime, then
            // take the maximum among them
            if (isPrime(Integer.parseInt(temp))
                && Integer.parseInt(temp) > maxPrime) {
                maxPrime = Integer.parseInt(temp);
                cost = i;
            }
 
            // Left rotation
            temp = temp.substring(1) + temp.charAt(0);
        }
 
        int optEle = maxPrime;
 
        // If no prime number can be obtained
        if (optEle == -1) {
            optEle = Integer.MAX_VALUE;
            temp = strN;
 
            // Check all the left
            // rotations of the number
            for (int i = 0; i < strN.length(); i++) {
 
                // Take the minimum element
                if (Integer.parseInt(temp) < optEle) {
                    optEle = Integer.parseInt(temp);
                    cost = i;
                }
 
                // Left rotation
                temp = temp.substring(1) + temp.charAt(0);
            }
            optEle *= (-1);
        }
        return new int[] { optEle, cost };
    }
 
    // Function to find the maximum sum
    // obtained using the given operations
    static void getMaxSum(int arr[])
    {
 
        // Store the maximum sum and
        // the number of operations
        int maxSum = 0, cost = 0;
 
        // Traverse array elements
        for (int x : arr) {
 
            // Get the optimal element and the
            // number of operations to obtain it
            int ret[] = rotateElement(x);
 
            int optEle = ret[0], optCost = ret[1];
 
            // Increment the maximum difference
            // and number of operations required
            maxSum += optEle;
            cost += optCost;
        }
 
        // Print the result
        System.out.println("Difference = " + maxSum + " , "
                           + "Count of operations = "
                           + cost);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array arr[]
        int arr[] = { 541, 763, 321, 716, 143 };
 
        // Function call
        getMaxSum(arr);
    }
}


Python3
# Python program for the above approach
 
# Fuction to check if a
# number is prime or not
def isPrime(n):
 
    # Base cases
    if (n <= 1):
        return False
    if (n <= 3):
        return True
 
    # Check if the number is
    # a multiple of 2 or 3
    if (n % 2 == 0 or n % 3 == 0):
        return False
 
    i = 5
 
    # Iterate until square root of n
    while(i * i <= n):
 
        # If n is divisible by both i and i + 2
        if (n % i == 0 or n % (i + 2) == 0):
            return False
        i = i + 6
 
    return True
 
# Function to left shift a number
# to maximize its contribution
def rotateElement(n):
 
        # Convert the number to string
    strN = str(n)
 
    # Stores the maximum prime number
    # that can be obtained from n
    maxPrime = -1
 
    # Store the required
    # number of operations
    cost = 0
 
    temp = str(strN)
 
    # Check for all the left
    # rotations of the number
    for i in range(len(strN)):
 
        # If the number is prime, then
        # take the maximum among them
        if isPrime(int(temp)) and int(temp) > maxPrime:
            maxPrime = int(temp)
            cost = i
 
        # Left rotation
        temp = temp[1:]+temp[:1]
 
    optEle = maxPrime
 
    # If no prime number can be obtained
    if optEle == -1:
        optEle = float('inf')
        temp = str(strN)
 
        # Check all the left
        # rotations of the number
        for i in range(len(strN)):
 
            # Take the minimum element
            if int(temp) < optEle:
                optEle = int(temp)
                cost = i
 
            # Left rotation
            temp = temp[1:]+temp[:1]
        optEle *= (-1)
 
    return (optEle, cost)
 
# Function to find the maximum sum
# obtained using the given operations
def getMaxSum(arr):
 
    # Store the maximum sum and
    # the number of operations
    maxSum, cost = 0, 0
 
    # Traverse array elements
    for x in arr:
 
        # Get the optimal element and the
        # number of operations to obtain it
        optEle, optCost = rotateElement(x)
 
        # Increment the maximum difference
        # and number of operations required
        maxSum += optEle
        cost += optCost
 
    # Print the result
    print('Difference =', maxSum, ',',
          'Count of operations =', cost)
 
 
# Driver Code
 
arr = [541, 763, 321, 716, 143]
getMaxSum(arr)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;                   
 
class GFG {
 
  // Fuction to check if a
  // number is prime or not
  static bool isPrime(int n)
  {
 
    // Base cases
    if (n <= 1)
      return false;
    if (n <= 3)
      return true;
 
    // Check if the number is
    // a multiple of 2 or 3
    if (n % 2 == 0 || n % 3 == 0)
      return false;
 
    int i = 5;
 
    // Iterate until square root of n
    while (i * i <= n) {
 
      // If n is divisible by both i and i + 2
      if (n % i == 0 || n % (i + 2) == 0)
        return false;
      i = i + 6;
    }
    return true;
  }
 
  // Function to left shift a number
  // to maximize its contribution
  static int[] rotateElement(int n)
  {
 
    // Convert the number to string
    string strN = n.ToString();
 
    // Stores the maximum prime number
    // that can be obtained from n
    int maxPrime = -1;
 
    // Store the required
    // number of operations
    int cost = 0;
 
    string temp = strN;
 
    // Check for all the left
    // rotations of the number
    for (int i = 0; i < strN.Length; i++) {
 
      // If the number is prime, then
      // take the maximum among them
      if (isPrime(Int32.Parse(temp))
          &&  Int32.Parse(temp) > maxPrime) {
        maxPrime =  Int32.Parse(temp);
        cost = i;
      }
 
      // Left rotation
      temp = temp.Substring(1) + temp[0];
    }
 
    int optEle = maxPrime;
 
    // If no prime number can be obtained
    if (optEle == -1) {
      optEle = 2147483647;
      temp = strN;
 
      // Check all the left
      // rotations of the number
      for (int i = 0; i < strN.Length; i++) {
 
        // Take the minimum element
        if (Int32.Parse(temp) < optEle) {
          optEle = Int32.Parse(temp);
          cost = i;
        }
 
        // Left rotation
        temp = temp.Substring(1) + temp[0];
      }
      optEle *= (-1);
    }
    return new int[] { optEle, cost };
  }
 
  // Function to find the maximum sum
  // obtained using the given operations
  static void getMaxSum(int []arr)
  {
 
    // Store the maximum sum and
    // the number of operations
    int maxSum = 0, cost = 0;
 
    // Traverse array elements
    foreach (int x in arr) {
 
      // Get the optimal element and the
      // number of operations to obtain it
      int[] ret = rotateElement(x);
 
      int optEle = ret[0], optCost = ret[1];
 
      // Increment the maximum difference
      // and number of operations required
      maxSum += optEle;
      cost += optCost;
    }
 
    // Print the result
    Console.Write("Difference = " + maxSum + " , "+ "Count of operations = "
                  + cost);
  }
 
  // Driver Code
  public static void Main()
  {
 
    // Given array arr[]
    int []arr = { 541, 763, 321, 716, 143 };
 
    // Function call
    getMaxSum(arr);
  }
}
 
// This code is contributed by ipg2016107.


输出:
Difference = 631 , Count of operations = 6

时间复杂度: O(N *√X* log(X)),其中X数组中最大的元素
辅助空间: O(1)