Sum of main diagonal elements in a Matrix which are prime

Given a matrix mat[][] of R rows and C columns. The task is to find the sum of all elements from the main diagonal which are prime numbers.
Note: The main diagonals are the ones that occur from Top Left of Matrix Down To Bottom Right Corner.

Examples:

Input: R = 3, C = 3, mat[][] = {{1, 2, 3}, {0, 1, 2}, {0, 4, 2}}
Output: 2
Explanation:
Elements from main diagonal are { 1, 1, 2}, out of these only ‘2’ is a prime number.
Therefore, the sum of diagonal elements which are prime = 2.

Input: R = 4, C = 4, mat[][] = { {1, 2, 3, 4}, { 0, 7, 21, 12}, { 1, 2, 3, 6}, { 3, 5, 2, 31}}
Output: 41
Explanation:
Elements from main diagonal are { 1, 7, 3, 31}, out of these {7, 3, 31} are prime numbers.
Therefore, the sum of diagonal elements which are prime = 7 + 3 + 31 = 41.

Naive Approach:



  1. Traverse the given matrix and check if the current element belongs to main diagonal or not.
  2. If element belongs to the main diagonal and it is a prime number then add value of the element to totalSum.
  3. After, traversal of the matrix print the value of totalSum.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function checks whether a number
// is prime or not
bool isPrime(int n)
{
    if (n < 2) {
        return false;
    }
  
    // Iterate to check primarility of n
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
  
    return true;
}
  
// Function calculates the sum of
// prime elements of main diagonal
void primeDiagonalElementSum(
    int* mat,
    int r, int c)
{
  
    // Initialise total sum as 0
    int totalSum = 0;
  
    // Iterate the given matrix mat[][]
    for (int i = 0; i < r; i++) {
  
        for (int j = 0; j < c; j++) {
  
            int temp = *((mat + i * c) + j);
  
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
  
    // Print the total sum
    cout << totalSum << endl;
}
  
// Driver Code
int main()
{
    int R = 4, C = 5;
  
    // Given Matrix
    int mat[4][5] = { { 1, 2, 3, 4, 2 },
                      { 0, 3, 2, 3, 9 },
                      { 0, 4, 1, 2, 8 },
                      { 1, 2, 3, 6, 6 } };
  
    // Function Call
    primeDiagonalElementSum((int*)mat, R, C);
    return 0;
}

chevron_right


Output:

3

Time Complexity: O(R*C*K), where K is the maximum element in the matrix.
Auxiliary Space: O(1)

Efficient Approach: We can optimize the naive approach by optimizing the primarility test of the number. Below are the steps for optimizing the primarility test:

  1. Instead of checking till N, we can check till sqrt(N) as the larger factor of N must be a multiple of smaller factor that has been already checked.
  2. The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4.
  3. As 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if N is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function checks whether a number
// is prime or not
bool isPrime(int n)
{
    // Corner cases
    if (n <= 1)
        return false;
    if (n <= 3)
        return true;
  
    // This is checked so that we can skip
    // middle five numbers in below loop
    if (n % 2 == 0 || n % 3 == 0)
        return false;
  
    for (int i = 5; i * i <= n; i = i + 6)
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
  
    return true;
}
  
// Function calculates the sum of
// prime elements of main diagonal
void primeDiagonalElementSum(
    int* mat,
    int r, int c)
{
  
    // Initialise total sum as 0
    int totalSum = 0;
  
    // Iterate the given matrix mat[][]
    for (int i = 0; i < r; i++) {
  
        for (int j = 0; j < c; j++) {
  
            int temp = *((mat + i * c) + j);
  
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
  
    // Print the total sum
    cout << totalSum << endl;
}
  
// Driver Code
int main()
{
    int R = 4, C = 5;
  
    // Given Matrix
    int mat[4][5] = { { 1, 2, 3, 4, 2 },
                      { 0, 3, 2, 3, 9 },
                      { 0, 4, 1, 2, 8 },
                      { 1, 2, 3, 6, 6 } };
  
    // Function Call
    primeDiagonalElementSum((int*)mat, R, C);
    return 0;
}

chevron_right


Output:

3

Time Complexity: O(R*C*sqrt(K)), where K is the maximum element in the matrix.
Auxiliary Space: O(1)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.