Check if Matrix sum is prime or not | C ++ implementation to check if the sum of matrix is prime or not ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function for to find the sum of the given matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 4 , M = 5 ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } int takeSum ( int a [ N ] [ M ] ) { int s = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) s += a [ i ] [ j ] ; return s ; } int main ( ) { int a [ N ] [ M ] = { { 1 , 2 , 3 , 4 , 2 } , { 0 , 1 , 2 , 3 , 34 } , { 0 , 34 , 21 , 12 , 12 } , { 1 , 2 , 3 , 6 , 6 } } ; int sum = takeSum ( a ) ; if ( isPrime ( sum ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }