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:
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++
#include <bits/stdc++.h>
using namespace std;
#define MAXN 100001
bool prime[MAXN];
void SieveOfEratosthenes()
{
int n = MAXN - 1;
memset (prime, true , sizeof (prime));
prime[0] = false ;
prime[1] = false ;
for ( int p = 2; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * p; i <= n; i += p)
prime[i] = false ;
}
}
}
void printPrimes(vector<vector< int > >& arr, int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (prime[arr[i][j]] == true ) {
cout << i + 1 << " " << j + 1 << " "
<< arr[i][j] << endl;
}
}
}
}
int main()
{
int N = 2;
vector<vector< int > > 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);
SieveOfEratosthenes();
printPrimes(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int MAXN = 100001 ;
static boolean prime[] = new boolean [MAXN];
static void SieveOfEratosthenes()
{
int n = MAXN - 1 ;
Arrays.fill(prime, true );
prime[ 0 ] = false ;
prime[ 1 ] = false ;
for ( int p = 2 ; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * p; i <= n; i = i + p)
prime[i] = false ;
}
}
}
static void printPrimes( int [][] arr, int n)
{
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++) {
if (prime[arr[i][j]] == 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();
}
}
}
}
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 ;
SieveOfEratosthenes();
printPrimes(arr, N);
}
}
|
Python3
import math
MAXN = 100001
prime = [ True for _ in range (MAXN)]
def SieveOfEratosthenes():
global prime
n = MAXN - 1
prime[ 0 ] = False
prime[ 1 ] = False
for p in range ( 2 , int (math.sqrt(n)) + 1 ):
if (prime[p] = = True ):
for i in range (p * p, n + 1 , p):
prime[i] = False
def printPrimes(arr, n):
for i in range ( 0 , n):
for j in range ( 0 , n):
if (prime[arr[i][j]] = = True ):
print (f "{i + 1} {j + 1} {arr[i][j]}" )
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())
SieveOfEratosthenes()
printPrimes(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int MAXN = 100001;
static bool [] prime = new bool [MAXN];
static void SieveOfEratosthenes()
{
int n = MAXN - 1;
Array.Fill(prime, true );
prime[0] = false ;
prime[1] = false ;
for ( int p = 2; p * p <= n; p++) {
if (prime[p] == true ) {
for ( int i = p * p; i <= n; i = i + p)
prime[i] = false ;
}
}
}
static void printPrimes( int [,] arr, int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (prime[arr[i,j]] == true ) {
Console.Write((i + 1));
Console.Write( " " );
Console.Write(j + 1);
Console.Write( " " );
Console.Write(arr[i,j]);
Console.WriteLine();
}
}
}
}
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;
SieveOfEratosthenes();
printPrimes(arr, N);
}
}
|
Javascript
<script>
let MAXN = 100001
let prime = new Array(MAXN).fill( true );
function SieveOfEratosthenes() {
let n = MAXN - 1;
prime[0] = false ;
prime[1] = false ;
for (let p = 2; p * p <= n; p++) {
if (prime[p] == true ) {
for (let i = p * p; i <= n; i = i + p)
prime[i] = false ;
}
}
}
function printPrimes(arr, n) {
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (prime[arr[i][j]] == true ) {
document.write((i + 1) + " " + (j + 1) + " "
+ (arr[i][j]) + "<br>" );
}
}
}
}
let N = 2;
let arr = new Array(N);
let temp = [1, 2]
arr[0] = temp;
let temp1 = [2, 1]
arr[1] = temp1;
SieveOfEratosthenes();
printPrimes(arr, N);
</script>
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...