The Wayback Machine - https://web.archive.org/web/20220113063116/https://www.geeksforgeeks.org/count-the-number-of-rows-and-columns-in-given-matrix-having-all-primes/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count the number of rows and columns in given Matrix having all primes

  • Last Updated : 12 Jan, 2022

Given a 2D matrix arr[] of size N*M, the task is to find the number of rows and columns having all primes.

Examples:

Input: arr[]= { { 2, 5, 7 }, { 3, 10, 4 }, { 11, 13, 17 } };
Output: 3
Explanation: 
2 Rows: {2, 5, 7}, {11, 13, 17}
1 Column: {2, 3, 11}

Input: arr[]={ { 1, 4 }, { 4, 6 } }
Output: 0

Approach: Follow the below steps to solve this problem:



  1. Apply the Sieve algorithm to find all prime numbers.
  2. Traverse all elements row-wise to find the number of rows having all primes.
  3. Apply the above step for all columns.
  4. Return the answer according to the above observation.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
#define MAXN 5000
  
bool prime[MAXN + 1];
  
// Seive to find prime numbers
void SieveOfEratosthenes(int n)
{
    memset(prime, true, sizeof(prime));
  
    for (int p = 2; p * p <= n; p++) {
  
        if (prime[p] == true) {
  
            for (int i = p * p; i <= n; i += p) {
                prime[i] = false;
            }
        }
    }
}
  
// Function to find the number of rows
// and columns having all primes
int primeRowCol(vector<vector<int> >& arr)
{
    int N = arr.size();
    int M = arr[0].size();
  
    SieveOfEratosthenes(MAXN);
  
    int cnt = 0;
  
    // Counting Rows with all primes
    for (int i = 0; i < N; i++) {
  
        bool flag = 1;
        for (int j = 0; j < M; ++j) {
            if (!prime[arr[i][j]]) {
                flag = 0;
                break;
            }
        }
        if (flag) {
            cnt += 1;
        }
    }
  
    // Counting Cols with all primes
    for (int i = 0; i < M; i++) {
  
        bool flag = 1;
        for (int j = 0; j < N; ++j) {
            if (!prime[arr[j][i]]) {
                flag = 0;
                break;
            }
        }
        if (flag) {
            cnt += 1;
        }
    }
  
    return cnt;
}
  
// Driver Code
int main()
{
  
    vector<vector<int> > arr
        = { { 2, 5, 7 }, { 3, 10, 4 }, { 11, 13, 17 } };
    cout << primeRowCol(arr);
}
Output
3

Time Complexity: O(N*M)
Auxiliary Space: O(max(arr))




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!