# Find Prime numbers in a 2D Array (Matrix)

• Last Updated : 29 Nov, 2021

Given a 2d array mat[][], the task is to find and print the prime numbers along with their position (1-based indexing) in this 2d array.

Examples:

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.

Input: mat[][] = {{1, 2}, {2, 1}}

Output:

1 2 2

2 1 2

Explanation:  First prime is at position row 1 and column 2 and the value is 2

Second prime is at position row 2 and column 1 and the value is 2

Input: mat[][] = {{1, 1}, {1, 1}}

Output: -1

Explanation:  There is no prime number in this 2d array

Naive Approach: The basic idea is to traverse the 2d array and for each number, check whether it is prime or not. If it is prime, print the position and the value for each found prime number.
Time Complexity: O(NM*sqrt(X)), where N*M is the size of the matrix and X is the largest element in the matrix
Auxiliary Space: O(1)

Efficient Approach: We can efficiently check if the number is prime or not using sieve. Then traverse the 2d array and simply check if the number is prime or not in O(1).

Follow the below steps for implementing this approach:

• Find the maximum element from the matrix and store it in a variable maxNum.
• Now find the prime numbers from 1 to maxNum using sieve of eratosthenes and store the result in array prime[].
• Now traverse the matrix and for each number check if it is a prime or not using the prime[] array.
• For each prime number in matrix print its position (row, column) and value.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the above approach``#include ``using` `namespace` `std;` `#define MAXN 100001``bool` `prime[MAXN];` `// Function to find prime numbers using sieve``void` `SieveOfEratosthenes()``{``    ``int` `n = MAXN - 1;` `    ``// Create a boolean array``    ``// "prime[0..n]" and initialize``    ``// all entries it as true.``    ``// A value in prime[i] will``    ``// finally be false if i is``    ``// Not a prime, else true.``    ``memset``(prime, ``true``, ``sizeof``(prime));``    ``prime[0] = ``false``;``    ``prime[1] = ``false``;` `    ``for` `(``int` `p = 2; p * p <= n; p++) {``        ``// If prime[p] is not changed,``        ``// then it is a prime``        ``if` `(prime[p] == ``true``) {``            ``// Update all multiples``            ``// of p greater than or``            ``// equal to the square of it``            ``// numbers which are multiple``            ``// of p and are less than p^2``            ``// are already been marked.``            ``for` `(``int` `i = p * p; i <= n; i += p)``                ``prime[i] = ``false``;``        ``}``    ``}``}` `// Function to print the position and``// value of the primes in given matrix``void` `printPrimes(vector >& arr, ``int` `n)``{``    ``// Traverse the matrix``    ``for` `(``int` `i = 0; i < n; i++) {``        ``for` `(``int` `j = 0; j < n; j++) {` `            ``// Check if the element is prime``            ``// or not in O(1)``            ``if` `(prime[arr[i][j]] == ``true``) {``                ``// Print the position and value``                ``// if found true``                ``cout << i + 1 << ``" "` `<< j + 1 << ``" "``                     ``<< arr[i][j] << endl;``            ``}``        ``}``    ``}``}` `// Driver Code``int` `main()``{``    ``int` `N = 2;``    ``vector > arr;``    ``vector<``int``> temp(N, 2);``    ``temp[0] = 1;``    ``temp[1] = 2;``    ``arr.push_back(temp);``    ``temp[0] = 2;``    ``temp[1] = 1;``    ``arr.push_back(temp);` `    ``// Precomputing prime numbers using sieve``    ``SieveOfEratosthenes();` `    ``// Find and print prime numbers``    ``// present in the matrix``    ``printPrimes(arr, N);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;` `class` `GFG {` `    ``static` `int` `MAXN = ``100001``;``    ``static` `boolean` `prime[] = ``new` `boolean``[MAXN];` `    ``// Function to find prime numbers using sieve``    ``static` `void` `SieveOfEratosthenes()``    ``{``        ``int` `n = MAXN - ``1``;``        ``Arrays.fill(prime, ``true``);``      ` `        ``// Create a boolean array``        ``// "prime[0..n]" and initialize``        ``// all entries it as true.``        ``// A value in prime[i] will``        ``// finally be false if i is``        ``// Not a prime, else true.``        ``prime[``0``] = ``false``;``        ``prime[``1``] = ``false``;` `        ``for` `(``int` `p = ``2``; p * p <= n; p++) {``            ``// If prime[p] is not changed,``            ``// then it is a prime``            ``if` `(prime[p] == ``true``) {``                ``// Update all multiples``                ``// of p greater than or``                ``// equal to the square of it``                ``// numbers which are multiple``                ``// of p and are less than p^2``                ``// are already been marked.``                ``for` `(``int` `i = p * p; i <= n; i = i + p)``                    ``prime[i] = ``false``;``            ``}``        ``}``    ``}` `    ``// Function to print the position and``    ``// value of the primes in given matrix``    ``static` `void` `printPrimes(``int``[][] arr, ``int` `n)``    ``{``        ``// Traverse the matrix``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``for` `(``int` `j = ``0``; j < n; j++) {` `                ``// Check if the element is prime``                ``// or not in O(1)``                ``if` `(prime[arr[i][j]] == ``true``) {``                    ``// Print the position and value``                    ``// if found true``                    ``System.out.print((i + ``1``));``                    ``System.out.print(``" "``);``                    ``System.out.print(j + ``1``);``                    ``System.out.print(``" "``);``                    ``System.out.print(arr[i][j]);``                    ``System.out.println();``                ``}``            ``}``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `N = ``2``;``        ``int` `arr[][] = ``new` `int``[N][N];` `        ``arr[``0``][``0``] = ``1``;``        ``arr[``0``][``1``] = ``2``;``        ``arr[``1``][``0``] = ``2``;``        ``arr[``1``][``1``] = ``1``;` `        ``// Precomputing prime numbers using sieve``        ``SieveOfEratosthenes();` `        ``// Find and print prime numbers``        ``// present in the matrix``        ``printPrimes(arr, N);``    ``}``}` `// This code is contributed by Potta Lokesh`

## Python3

 `# python code to implement the above approach``import` `math``MAXN ``=` `100001``prime ``=` `[``True` `for` `_ ``in` `range``(MAXN)]` `# Function to find prime numbers using sieve``def` `SieveOfEratosthenes():``    ``global` `prime` `    ``n ``=` `MAXN ``-` `1` `    ``# Create a boolean array``    ``# "prime[0..n]" and initialize``    ``# all entries it as true.``    ``# A value in prime[i] will``    ``# finally be false if i is``    ``# Not a prime, else true.``    ``prime[``0``] ``=` `False``    ``prime[``1``] ``=` `False` `    ``for` `p ``in` `range``(``2``, ``int``(math.sqrt(n)) ``+` `1``):``      ` `                ``# If prime[p] is not changed,``                ``# then it is a prime``        ``if` `(prime[p] ``=``=` `True``):``          ` `           ``# Update all multiples``           ``# of p greater than or``           ``# equal to the square of it``           ``# numbers which are multiple``           ``# of p and are less than p^2``           ``# are already been marked.``            ``for` `i ``in` `range``(p``*``p, n``+``1``, p):``                ``prime[i] ``=` `False` `# Function to print the position and``# value of the primes in given matrix``def` `printPrimes(arr, n):` `        ``# Traverse the matrix``    ``for` `i ``in` `range``(``0``, n):``        ``for` `j ``in` `range``(``0``, n):` `                        ``# Check if the element is prime``                        ``# or not in O(1)``            ``if` `(prime[arr[i][j]] ``=``=` `True``):``              ` `                ``# Print the position and value``                ``# if found true``                ``print``(f``"{i + 1} {j + 1} {arr[i][j]}"``)` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``N ``=` `2``    ``arr ``=` `[]``    ``temp ``=` `[``2` `for` `_ ``in` `range``(N)]``    ` `    ``temp[``0``] ``=` `1``    ``temp[``1``] ``=` `2``    ``arr.append(temp.copy())``    ``temp[``0``] ``=` `2``    ``temp[``1``] ``=` `1``    ``arr.append(temp.copy())` `    ``# Precomputing prime numbers using sieve``    ``SieveOfEratosthenes()` `    ``# Find and print prime numbers``    ``# present in the matrix``    ``printPrimes(arr, N)` `    ``# This code is contributed by rakeshsahni`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;``class` `GFG {` `    ``static` `int` `MAXN = 100001;``    ``static` `bool``[] prime = ``new` `bool``[MAXN];` `    ``// Function to find prime numbers using sieve``    ``static` `void` `SieveOfEratosthenes()``    ``{``        ``int` `n = MAXN - 1;``        ``Array.Fill(prime, ``true``);``      ` `        ``// Create a boolean array``        ``// "prime[0..n]" and initialize``        ``// all entries it as true.``        ``// A value in prime[i] will``        ``// finally be false if i is``        ``// Not a prime, else true.``        ``prime[0] = ``false``;``        ``prime[1] = ``false``;` `        ``for` `(``int` `p = 2; p * p <= n; p++) {``            ``// If prime[p] is not changed,``            ``// then it is a prime``            ``if` `(prime[p] == ``true``) {``                ``// Update all multiples``                ``// of p greater than or``                ``// equal to the square of it``                ``// numbers which are multiple``                ``// of p and are less than p^2``                ``// are already been marked.``                ``for` `(``int` `i = p * p; i <= n; i = i + p)``                    ``prime[i] = ``false``;``            ``}``        ``}``    ``}` `    ``// Function to print the position and``    ``// value of the primes in given matrix``    ``static` `void` `printPrimes(``int``[,] arr, ``int` `n)``    ``{``        ``// Traverse the matrix``        ``for` `(``int` `i = 0; i < n; i++) {``            ``for` `(``int` `j = 0; j < n; j++) {` `                ``// Check if the element is prime``                ``// or not in O(1)``                ``if` `(prime[arr[i,j]] == ``true``) {``                    ``// Print the position and value``                    ``// if found true``                    ``Console.Write((i + 1));``                    ``Console.Write(``" "``);``                    ``Console.Write(j + 1);``                    ``Console.Write(``" "``);``                    ``Console.Write(arr[i,j]);``                    ``Console.WriteLine();``                ``}``            ``}``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int` `N = 2;``        ``int``[,] arr = ``new` `int``[N,N];` `        ``arr[0,0] = 1;``        ``arr[0,1] = 2;``        ``arr[1,0] = 2;``        ``arr[1,1] = 1;` `        ``// Precomputing prime numbers using sieve``        ``SieveOfEratosthenes();` `        ``// Find and print prime numbers``        ``// present in the matrix``        ``printPrimes(arr, N);``    ``}``}` `// This code is contributed by Saurabh Jaiswal`

## Javascript

 ``

Output
```1 2 2
2 1 2```

Time Complexity: O(N*M) where N*M is the size of matrix.
Auxiliary Space: O(maxNum) where maxNum is the largest element in the matrix.

My Personal Notes arrow_drop_up