Insert minimum number in array so that sum of array becomes prime
Last Updated :
18 Jan, 2024
Given an array of n integers. Find minimum number to be inserted in array, so that sum of all elements of array becomes prime. If sum is already prime, then return 0.
Examples :
Input : arr[] = { 2, 4, 6, 8, 12 }
Output : 5
Input : arr[] = { 3, 5, 7 }
Output : 0
Naive approach: The simplest approach to solve this problem is to first find the sum of array elements. Then check if this sum is prime or not, if sum is prime return zero otherwise find prime number just greater than this sum. We can find prime number greater than sum by checking if a number is prime or not from (sum+1) until we find a prime number. Once a prime number just greater than sum is found, return difference of sum and this prime number.
Below is implementation of above idea:
C++
// C++ program to find minimum number to
// insert in array so their sum is prime
#include <bits/stdc++.h>
using namespace std;
// function to check if a
// number is prime or not
bool isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n - 1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Find prime number
// greater than a number
int findPrime(int n)
{
int num = n + 1;
// find prime greater than n
while (num)
{
// check if num is prime
if (isPrime(num))
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
int minNumber(int arr[], int n)
{
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
// if sum is already prime
// return 0
if (isPrime(sum))
return 0;
// To find prime number
// greater than sum
int num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver code
int main()
{
int arr[] = { 2, 4, 6, 8, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minNumber(arr, n);
return 0;
}
Java
// Java program to find minimum number to
// insert in array so their sum is prime
class GFG
{
// function to check if a
// number is prime or not
static boolean isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n - 1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Find prime number
// greater than a number
static int findPrime(int n)
{
int num = n + 1;
// find prime greater than n
while (num > 0)
{
// check if num is prime
if (isPrime(num))
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
static int minNumber(int arr[], int n)
{
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
// if sum is already prime
// return 0
if (isPrime(sum))
return 0;
// To find prime number
// greater than sum
int num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver Code
public static void main(String[]args)
{
int arr[] = { 2, 4, 6, 8, 12 };
int n = arr.length;
System.out.println(minNumber(arr, n));
}
}
// This code is contributed by Azkia Anam.
Python3
# Python3 program to find minimum number to
# insert in array so their sum is prime
# function to check if a
# number is prime or not
def isPrime(n):
# Corner case
if n <= 1:
return False
# Check from 2 to n - 1
for i in range(2, n):
if n % i == 0:
return False
return True
# Find prime number
# greater than a number
def findPrime(n):
num = n + 1
# find prime greater than n
while (num):
# check if num is prime
if isPrime(num):
return num
# Increment num
num += 1
return 0
# To find number to be added
# so sum of array is prime
def minNumber(arr):
s = 0
# To find sum of array elements
for i in range(0, len(arr)):
s += arr[i]
# If sum is already prime
# return 0
if isPrime(s) :
return 0
# To find prime number
# greater than sum
num = findPrime(s)
# Return difference of sum and num
return num - s
# Driver code
arr = [ 2, 4, 6, 8, 12 ]
print (minNumber(arr))
# This code is contributed by Sachin Bisht
C#
// C# program to find minimum number to
// insert in array so their sum is prime
using System;
class GFG
{
// function to check if a
// number is prime or not
static bool isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n - 1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Find prime number
// greater than a number
static int findPrime(int n)
{
int num = n + 1;
// find prime greater than n
while (num > 0)
{
// check if num is prime
if (isPrime(num))
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
static int minNumber(int []arr, int n)
{
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
// if sum is already prime
// return 0
if (isPrime(sum))
return 0;
// To find prime number
// greater than sum
int num = findPrime(sum);
// Return difference of sum and num
return num - sum;
}
// Driver Code
public static void Main()
{
int []arr = { 2, 4, 6, 8, 12 };
int n = arr.Length;
Console.Write(minNumber(arr, n));
}
}
// This code is contributed by nitin mittal
PHP
<?php
// PHP program to find minimum number to
// insert in array so their sum is prime
// function to check if a
// number is prime or not
function isPrime($n)
{
// Corner case
if ($n <= 1)
return false;
// Check from 2 to n - 1
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
// Find prime number
// greater than a number
function findPrime($n)
{
$num = $n + 1;
// find prime greater than n
while ($num)
{
// check if num is prime
if (isPrime($num))
return $num;
// increment num
$num = $num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
function minNumber($arr, $n)
{
$sum = 0;
// To find sum of array elements
for ($i = 0; $i < $n; $i++)
$sum += $arr[$i];
// if sum is already prime
// return 0
if (isPrime($sum))
return 0;
// To find prime number
// greater than sum
$num = findPrime($sum);
// Return difference of
// sum and num
return $num - $sum;
}
// Driver Code
$arr = array(2, 4, 6, 8, 12);
$n = sizeof($arr);
echo minNumber($arr, $n);
// This code is contributed by nitin mittal
?>
JavaScript
<script>
// Javascript program to find minimum number to
// insert in array so their sum is prime
// function to check if a
// number is prime or not
function isPrime(n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n - 1
for (let i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
// Find prime number
// greater than a number
function findPrime(n)
{
let num = n + 1;
// find prime greater than n
while (num > 0)
{
// check if num is prime
if (isPrime(num))
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
function minNumber(arr,n)
{
let sum = 0;
// To find sum of array elements
for (let i = 0; i < n; i++)
sum += arr[i];
// if sum is already prime
// return 0
if (isPrime(sum))
return 0;
// To find prime number
// greater than sum
let num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver Code
let arr=[2, 4, 6, 8, 12 ];
let n = arr.length;
document.write(minNumber(arr, n));
//This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O( N2 )
Efficient Approach: We can optimize the above approach by efficiently pre calculating a large boolean array to check if a number is prime or not using sieve of eratosthenes. Once all prime number are generated, find prime number just greater than sum and return the difference between them.
Below is the implementation of this approach:
C++
// C++ program to find minimum number to
// insert in array so their sum is prime
#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
// Array to store primes
bool isPrime[MAX];
// function to calculate primes
// using sieve of eratosthenes
void sieveOfEratostheneses()
{
memset(isPrime, true, sizeof(isPrime));
isPrime[1] = false;
for (int i = 2; i * i < MAX; i++)
{
if (isPrime[i])
{
for (int j = 2 * i; j < MAX; j += i)
isPrime[j] = false;
}
}
}
// Find prime number
// greater than a number
int findPrime(int n)
{
int num = n + 1;
// To return prime number
// greater than n
while (num)
{
// check if num is prime
if (isPrime[num])
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
int minNumber(int arr[], int n)
{
// call sieveOfEratostheneses
// to calculate primes
sieveOfEratostheneses();
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
if (isPrime[sum])
return 0;
// To find prime number
// greater then sum
int num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver Code
int main()
{
int arr[] = { 2, 4, 6, 8, 12 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minNumber(arr, n);
return 0;
}
Java
// Java program to find minimum number to
// insert in array so their sum is prime
class GFG
{
static int MAX = 100005;
// Array to store primes
static boolean[] isPrime = new boolean[MAX];
// function to calculate primes
// using sieve of eratosthenes
static void sieveOfEratostheneses()
{
isPrime[1] = true;
for (int i = 2; i * i < MAX; i++)
{
if (!isPrime[i])
{
for (int j = 2 * i; j < MAX; j += i)
isPrime[j] = true;
}
}
}
// Find prime number greater
// than a number
static int findPrime(int n)
{
int num = n + 1;
// To return prime number
// greater than n
while (num > 0)
{
// check if num is prime
if (!isPrime[num])
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
static int minNumber(int arr[], int n)
{
// call sieveOfEratostheneses
// to calculate primes
sieveOfEratostheneses();
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
if (!isPrime[sum])
return 0;
// To find prime number
// greater then sum
int num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 2, 4, 6, 8, 12 };
int n = arr.length;
System.out.println(minNumber(arr, n));
}
}
// This code is contributed by mits
Python3
# Python3 program to find minimum number to
# insert in array so their sum is prime
isPrime = [1] * 100005
# function to calculate prime
# using sieve of eratosthenes
def sieveOfEratostheneses():
isPrime[1] = False
i = 2
while i * i < 100005:
if(isPrime[i]):
j = 2 * i
while j < 100005:
isPrime[j] = False
j += i
i += 1
return
# Find prime number
# greater than a number
def findPrime(n):
num = n + 1
# find prime greater than n
while(num):
# check if num is prime
if isPrime[num]:
return num
# Increment num
num += 1
return 0
# To find number to be added
# so sum of array is prime
def minNumber(arr):
# call sieveOfEratostheneses to
# calculate primes
sieveOfEratostheneses()
s = 0
# To find sum of array elements
for i in range(0, len(arr)):
s += arr[i]
# If sum is already prime
# return 0
if isPrime[s] == True:
return 0
# To find prime number
# greater than sum
num = findPrime(s)
# Return difference of
# sum and num
return num - s
# Driver code
arr = [ 2, 4, 6, 8, 12 ]
print (minNumber(arr))
# This code is contributed by Sachin Bisht
C#
// C# program to find minimum number to
// insert in array so their sum is prime
class GFG
{
static int MAX = 100005;
// Array to store primes
static bool[] isPrime = new bool[MAX];
// function to calculate primes
// using sieve of eratosthenes
static void sieveOfEratostheneses()
{
isPrime[1] = true;
for (int i = 2; i * i < MAX; i++)
{
if (!isPrime[i])
{
for (int j = 2 * i; j < MAX; j += i)
isPrime[j] = true;
}
}
}
// Find prime number greater
// than a number
static int findPrime(int n)
{
int num = n + 1;
// To return prime number
// greater than n
while (num > 0)
{
// check if num is prime
if (!isPrime[num])
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
static int minNumber(int[] arr, int n)
{
// call sieveOfEratostheneses
// to calculate primes
sieveOfEratostheneses();
int sum = 0;
// To find sum of array elements
for (int i = 0; i < n; i++)
sum += arr[i];
if (!isPrime[sum])
return 0;
// To find prime number
// greater then sum
int num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// Driver Code
public static void Main()
{
int[] arr = { 2, 4, 6, 8, 12 };
int n = arr.Length;
System.Console.WriteLine(minNumber(arr, n));
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to find minimum number to
// insert in array so their sum is prime
$MAX =100005;
// function to calculate primes
// using sieve of eratosthenes
function sieveOfEratostheneses()
{
$isPrime = array_fill(true,$MAX, NULL);
$isPrime[1] = false;
for ($i = 2; $i * $i < $MAX; $i++)
{
if ($isPrime[$i])
{
for ($j = 2 * $i; $j < $MAX; $j += $i)
$isPrime[$j] = false;
}
}
}
// Find prime number
// greater than a number
function findPrime($n)
{
$num = $n + 1;
// To return prime number
// greater than n
while ($num)
{
// check if num is prime
if ($isPrime[$num])
return $num;
// increment num
$num = $num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
function minNumber(&$arr, $n)
{
// call sieveOfEratostheneses
// to calculate primes
sieveOfEratostheneses();
$sum = 0;
// To find sum of array elements
for ($i = 0; $i < $n; $i++)
$sum += $arr[$i];
if ($isPrime[$sum])
return 0;
// To find prime number
// greater then sum
$num = findPrime($sum);
// Return difference of
// sum and num
return $num - $sum;
}
// Driver Code
$arr = array ( 2, 4, 6, 8, 12 );
$n = sizeof($arr) / sizeof($arr[0]);
echo minNumber($arr, $n);
return 0;
?>
JavaScript
<script>
// Javascript program to find minimum number to
// insert in array so their sum is prime
let MAX = 100005;
// Array to store primes
let isPrime = new Array(MAX).fill(0);
// function to calculate primes
// using sieve of eratosthenes
function sieveOfEratostheneses()
{
isPrime[1] = true;
for (let i = 2; i * i < MAX; i++)
{
if (!isPrime[i])
{
for (let j = 2 * i; j < MAX; j += i)
isPrime[j] = true;
}
}
}
// Find prime number greater
// than a number
function findPrime(n)
{
let num = n + 1;
// To return prime number
// greater than n
while (num > 0)
{
// check if num is prime
if (!isPrime[num])
return num;
// increment num
num = num + 1;
}
return 0;
}
// To find number to be added
// so sum of array is prime
function minNumber(arr, n)
{
// call sieveOfEratostheneses
// to calculate primes
sieveOfEratostheneses();
let sum = 0;
// To find sum of array elements
for (let i = 0; i < n; i++)
sum += arr[i];
if (!isPrime[sum])
return 0;
// To find prime number
// greater then sum
let num = findPrime(sum);
// Return difference of
// sum and num
return num - sum;
}
// driver program
let arr = [ 2, 4, 6, 8, 12 ];
let n = arr.length;
document.write(minNumber(arr, n));
// This code is contributed by code_hunt.
</script>
Time Complexity: O(N log(log N))
Transform to prime | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem