Check if diagonal elements of a Matrix are Prime or not | C ++ program for the above approach ; Stores if a number is prime or not ; Function to generate and store primes using Sieve Of Eratosthenes ; Set all numbers as prime ; If p is a prime ; Set all its multiples as non - prime ; Function to check if all diagonal elements are prime or not ; Stores if all diagonal elements are prime or not ; Precompute primes ; Traverse the range [ 0 , N - 1 ] ; Check if numbers on the cross diagonal and main diagonal are primes or not ; If true , then print " Yes " ; Otherwise , print " No " ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 1000005 ] ; void SieveOfEratosthenes ( int N ) { 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 checkElementsOnDiagonal ( vector < vector < int > > M , int N ) { int flag = 1 ; SieveOfEratosthenes ( 1000000 ) ; for ( int i = 0 ; i < N ; i ++ ) { flag &= ( prime [ M [ i ] [ i ] ] && prime [ M [ i ] [ N - 1 - i ] ] ) ; } if ( flag ) cout << " Yes " << endl ; else cout << " No " ; } int main ( ) { vector < vector < int > > M = { { 1 , 2 , 3 , 13 } , { 5 , 3 , 7 , 8 } , { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 7 } } ; int N = M . size ( ) ; checkElementsOnDiagonal ( M , N ) ; return 0 ; }