Skip to content
Related Articles

Related Articles

Improve Article

Minimum prime numbers required to be subtracted to make all array elements equal

  • Last Updated : 31 Aug, 2021

Given an array arr[] consisting of N positive integers, the task is to find the minimum number of primes numbers required to be subtracted from the array elements to make all array elements equal.

Examples:

Input: arr[]= {7, 10, 4, 5}
Output: 5
Explanation: Following subtraction of primes numbers makes all array elements equal:

  1. Subtracting 5 from arr[0] modifies arr[] to {2, 10, 4, 5}.
  2. Subtracting 5 from arr[1] modifies arr[] to {2, 5, 4, 5}.
  3. Subtracting 3 from arr[1] modifies arr[] to {2, 2, 4, 5}.
  4. Subtracting 2 from arr[2] modifies arr[] to {2, 2, 2, 5}.
  5. Subtracting 3 from arr[3] modifies arr[] to {2, 2, 2, 2}.

Therefore, the total numbers of operations required is 5.

Input: arr[]= {10, 17, 37, 43, 50}
Output: 8



Approach: The given problem can be solved using the below observations:

  • Every even number greater than 2 is the sum of two prime numbers.
  • Every odd number greater than 1, can be represented as the sum of at most 3 prime numbers. Below are the possible cases for the same:
    • Case 1: If N is prime.
    • Case 2: If (N – 2) is prime. Therefore, 2 numbers required i.e., 2 and N – 2.
    • Case 3: If (N – 3) is even, then using Goldbach’s conjecture. (N – 3) can be represented as the sum of two prime numbers.
  • Therefore, the idea is to reduce each array element to the minimum value of the array(say M) arr[] and if there exists an element in the array having value (M + 1) then reduce each element to the value (M – 2).

Follow the steps below to solve this problem:

  • Initialize an array, say prime[], of size 105, to store at every ith index, whether i is prime number or not using Sieve Of Eratosthenes.
  • Find the minimum element present in the array, say M.
  • If there exists any element in the array arr[] with value (M + 1), then update M to (M – 2).
  • Initialize a variable, say count, to store the number of operations required to make all array elements equal.
  • Traverse the given array arr[] and perform the following steps:
    • Find the difference between arr[i] and M, say D.
    • Update the value of count according to the following values of D:
      • If the value of D is a prime number, then increment count by 1.
      • If the value of D is an even number, then increment count by 2.
      • If the value of D is an odd number, and if (D – 2) is a prime number, then increment count by 2. Otherwise, increment count by 3.
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#define limit 100000
using namespace std;
 
// Stores the sieve of prime numbers
bool prime[limit + 1];
 
// Function that performs the Sieve of
// Eratosthenes
void sieve()
{
    // Initialize all numbers as prime
    memset(prime, true, sizeof(prime));
 
    // Iterate over the range [2, 1000]
    for (int p = 2; p * p <= limit; p++) {
 
        // If the current element
        // is a prime number
        if (prime[p] == true) {
 
            // Mark all its multiples as false
            for (int i = p * p; i <= limit; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the minimum number of
// subtraction of primes numbers required
// to make all array elements the same
int findOperations(int arr[], int n)
{
    // Perform sieve of eratosthenes
    sieve();
 
    int minm = INT_MAX;
 
    // Find the minimum value
    for (int i = 0; i < n; i++) {
        minm = min(minm, arr[i]);
    }
 
    // Stores the value to each array
    // element should be reduced
    int val = minm;
 
    for (int i = 0; i < n; i++) {
 
        // If an element exists with
        // value (M + 1)
        if (arr[i] == minm + 1) {
            val = minm - 2;
            break;
        }
    }
 
    // Stores the minimum count of
    // subtraction of prime numbers
    int cnt = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        int D = arr[i] - val;
 
        // If D is equal to 0
        if (D == 0) {
            continue;
        }
 
        // If D is a prime number
        else if (prime[D] == true) {
 
            // Increase count by 1
            cnt += 1;
        }
 
        // If D is an even number
        else if (D % 2 == 0) {
 
            // Increase count by 2
            cnt += 2;
        }
        else {
 
            // If D - 2 is prime
            if (prime[D - 2] == true) {
 
                // Increase count by 2
                cnt += 2;
            }
 
            // Otherwise, increase
            // count by 3
            else {
                cnt += 3;
            }
        }
    }
 
    return cnt;
}
 
// Driver Code
int main()
{
    int arr[] = { 7, 10, 4, 5 };
    int N = 4;
    cout << findOperations(arr, N);
 
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
static int limit = 100000;
 
// Stores the sieve of prime numbers
static boolean prime[];
 
// Function that performs the Sieve of
// Eratosthenes
static void sieve()
{
    prime = new boolean[limit + 1];
 
    // Initialize all numbers as prime
    Arrays.fill(prime, true);
 
    // Iterate over the range [2, 1000]
    for(int p = 2; p * p <= limit; p++)
    {
         
        // If the current element
        // is a prime number
        if (prime[p] == true)
        {
             
            // Mark all its multiples as false
            for(int i = p * p; i <= limit; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the minimum number of
// subtraction of primes numbers required
// to make all array elements the same
static int findOperations(int arr[], int n)
{
     
    // Perform sieve of eratosthenes
    sieve();
 
    int minm = Integer.MAX_VALUE;
 
    // Find the minimum value
    for(int i = 0; i < n; i++)
    {
        minm = Math.min(minm, arr[i]);
    }
 
    // Stores the value to each array
    // element should be reduced
    int val = minm;
 
    for(int i = 0; i < n; i++)
    {
         
        // If an element exists with
        // value (M + 1)
        if (arr[i] == minm + 1)
        {
            val = minm - 2;
            break;
        }
    }
 
    // Stores the minimum count of
    // subtraction of prime numbers
    int cnt = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int D = arr[i] - val;
 
        // If D is equal to 0
        if (D == 0)
        {
            continue;
        }
 
        // If D is a prime number
        else if (prime[D] == true)
        {
             
            // Increase count by 1
            cnt += 1;
        }
 
        // If D is an even number
        else if (D % 2 == 0)
        {
             
            // Increase count by 2
            cnt += 2;
        }
        else
        {
             
            // If D - 2 is prime
            if (prime[D - 2] == true)
            {
                 
                // Increase count by 2
                cnt += 2;
            }
 
            // Otherwise, increase
            // count by 3
            else
            {
                cnt += 3;
            }
        }
    }
    return cnt;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 7, 10, 4, 5 };
    int N = 4;
     
    System.out.println(findOperations(arr, N));
}
}
 
// This code is contributed by Kingash

Python3




# Python3 program for the above approach
import sys
 
limit = 100000
 
# Stores the sieve of prime numbers
prime = [True] * (limit + 1)
 
# Function that performs the Sieve of
# Eratosthenes
def sieve():
 
    # Iterate over the range [2, 1000]
    p = 2
    while(p * p <= limit):
 
        # If the current element
        # is a prime number
        if (prime[p] == True):
 
            # Mark all its multiples as false
            for i in range(p * p, limit, p):
                prime[i] = False
         
        p += 1
     
# Function to find the minimum number of
# subtraction of primes numbers required
# to make all array elements the same
def findOperations(arr, n):
     
    # Perform sieve of eratosthenes
    sieve()
 
    minm = sys.maxsize
 
    # Find the minimum value
    for i in range(n):
        minm = min(minm, arr[i])
     
    # Stores the value to each array
    # element should be reduced
    val = minm
 
    for i in range(n):
 
        # If an element exists with
        # value (M + 1)
        if (arr[i] == minm + 1):
            val = minm - 2
            break
         
    # Stores the minimum count of
    # subtraction of prime numbers
    cnt = 0
 
    # Traverse the array
    for i in range(n):
        D = arr[i] - val
 
        # If D is equal to 0
        if (D == 0):
            continue
         
        # If D is a prime number
        elif (prime[D] == True):
 
            # Increase count by 1
            cnt += 1
         
        # If D is an even number
        elif (D % 2 == 0):
 
            # Increase count by 2
            cnt += 2
         
        else:
 
            # If D - 2 is prime
            if (prime[D - 2] == True):
                 
                # Increase count by 2
                cnt += 2
 
            # Otherwise, increase
            # count by 3
            else:
                cnt += 3
 
    return cnt
 
# Driver Code
arr = [ 7, 10, 4, 5 ]
N = 4
 
print(findOperations(arr, N))
 
# This code is contributed by splevel62

C#




// C# program for the above approach
using System;
 
class GFG{
 
static int limit = 100000;
 
// Stores the sieve of prime numbers
static bool[] prime;
 
// Function that performs the Sieve of
// Eratosthenes
static void sieve()
{
    prime = new bool[limit + 1];
 
    // Initialize all numbers as prime
    Array.Fill(prime, true);
 
    // Iterate over the range [2, 1000]
    for(int p = 2; p * p <= limit; p++)
    {
         
        // If the current element
        // is a prime number
        if (prime[p] == true)
        {
             
            // Mark all its multiples as false
            for(int i = p * p; i <= limit; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the minimum number of
// subtraction of primes numbers required
// to make all array elements the same
static int findOperations(int[] arr, int n)
{
     
    // Perform sieve of eratosthenes
    sieve();
 
    int minm = Int32.MaxValue;
 
    // Find the minimum value
    for(int i = 0; i < n; i++)
    {
        minm = Math.Min(minm, arr[i]);
    }
 
    // Stores the value to each array
    // element should be reduced
    int val = minm;
 
    for(int i = 0; i < n; i++)
    {
         
        // If an element exists with
        // value (M + 1)
        if (arr[i] == minm + 1)
        {
            val = minm - 2;
            break;
        }
    }
 
    // Stores the minimum count of
    // subtraction of prime numbers
    int cnt = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int D = arr[i] - val;
 
        // If D is equal to 0
        if (D == 0)
        {
            continue;
        }
 
        // If D is a prime number
        else if (prime[D] == true)
        {
             
            // Increase count by 1
            cnt += 1;
        }
 
        // If D is an even number
        else if (D % 2 == 0)
        {
             
            // Increase count by 2
            cnt += 2;
        }
        else
        {
             
            // If D - 2 is prime
            if (prime[D - 2] == true)
            {
                 
                // Increase count by 2
                cnt += 2;
            }
 
            // Otherwise, increase
            // count by 3
            else
            {
                cnt += 3;
            }
        }
    }
    return cnt;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 7, 10, 4, 5 };
    int N = 4;
 
    Console.WriteLine(findOperations(arr, N));
}
}
 
// This code is contributed by ukasp

Javascript




<script>
 
// Javascript program for the above approach
 
var limit = 100000;
 
// Stores the sieve of prime numbers
var prime = Array(limit + 1).fill(true);
 
// Function that performs the Sieve of
// Eratosthenes
function sieve()
{
 
    // Iterate over the range [2, 1000]
    for (p = 2; p * p <= limit; p++) {
 
        // If the current element
        // is a prime number
        if (prime[p] == true) {
 
            // Mark all its multiples as false
            for (i = p * p; i <= limit; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the minimum number of
// subtraction of primes numbers required
// to make all array elements the same
function findOperations(arr, n)
{
    // Perform sieve of eratosthenes
    sieve();
 
    var minm = Number.MAX_VALUE;
 
    // Find the minimum value
    for (i = 0; i < n; i++) {
        minm = Math.min(minm, arr[i]);
    }
 
    // Stores the value to each array
    // element should be reduced
    var val = minm;
 
    for (i = 0; i < n; i++) {
 
        // If an element exists with
        // value (M + 1)
        if (arr[i] == minm + 1) {
            val = minm - 2;
            break;
        }
    }
 
    // Stores the minimum count of
    // subtraction of prime numbers
    var cnt = 0;
 
    // Traverse the array
    for (i = 0; i < n; i++) {
 
        var D = arr[i] - val;
 
        // If D is equal to 0
        if (D == 0) {
            continue;
        }
 
        // If D is a prime number
        else if (prime[D] == true) {
 
            // Increase count by 1
            cnt += 1;
        }
 
        // If D is an even number
        else if (D % 2 == 0) {
 
            // Increase count by 2
            cnt += 2;
        }
        else {
 
            // If D - 2 is prime
            if (prime[D - 2] == true) {
 
                // Increase count by 2
                cnt += 2;
            }
 
            // Otherwise, increase
            // count by 3
            else {
                cnt += 3;
            }
        }
    }
 
    return cnt;
}
 
// Driver Code
 
    var arr = [7, 10, 4, 5];
    var N = 4;
    document.write(findOperations(arr, N));
 
</script>
Output: 
5

 

Time Complexity: O(N + M * log(log(M))), M is the size of 
Auxiliary Space: O(M)

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :