📜  检查矩阵的对角线元素是否为素数

📅  最后修改于: 2021-09-08 12:41:11             🧑  作者: Mango

给定一个维度为N*N的矩阵M[][] ,任务是检查矩阵的主对角线上和交叉对角线上的所有元素是否都是素数。如果发现是真的,则打印“是” 。否则打印“否”。

例子:

方法:这个想法是使用埃拉托色尼筛来检查一个数是否为素数。请按照以下步骤解决问题:

  • 使用埃拉托色尼筛法预先计算并存储素数。
  • 使用变量i在范围[0, N – 1] 上迭代一个循环并执行以下操作:
    • 检查 M[i][i],即主对角线上的一个元素,是否是素数。
    • 检查M[i][N – 1 – i],即交叉对角线上的一个元素,是否是素数。
    • 如果不满足以上两个条件中的任何一个,则打印“NO”并中断。
  • 否则,打印“YES”

下面是上述方法的实现:

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


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG
{
 
// Stores if a number is prime or not
static boolean[] prime = new boolean[1000005];
  
// Function to generate and store
// primes using Sieve Of Eratosthenes
static void SieveOfEratosthenes(int N)
{
   
    // Set all numbers as prime
    Arrays.fill(prime, true);
 
    prime[0] = false;
    prime[1] = false;
  
    for (int p = 2; p * p <= N; p++) {
  
        // If p is a prime
        if (prime[p] == true) {
  
            // Set all its multiples
            // as non-prime
            for (int i = p * p;
                 i <= N; i += p)
  
                prime[i] = false;
        }
    }
}
  
// Function to check if all diagonal
// elements are prime or not
static void checkElementsOnDiagonal(int[][] M, int N)
{
   
    // Stores if all diagonal
    // elements are prime or not
    int flag = 1;
  
    // Precompute primes
    SieveOfEratosthenes(1000000);
  
    // Traverse the range [0, N-1]
    for (int i = 0; i < N; i++) {
  
        // Check if numbers on the cross
        // diagonal and main diagonal
        // are primes or not
        boolean flg = (boolean)(prime[M[i][i]]
                && prime[M[i][N - 1 - i]]);
        int val = (flg) ? 1 : 0;
        flag &= val;
    }
  
    // If true, then print "Yes"
    if (flag != 0)
        System.out.print("Yes");
  
    // Otherwise, print "No"
    else
        System.out.print("No");
}
 
 
// Driver Code
public static void main (String[] args)
{
     
    int[][] M = {
        { 1, 2, 3, 13 },
        { 5, 3, 7, 8 },
        { 1, 2, 3, 4 },
        { 5, 6, 7, 7 }
    };
    int N = M.length;
  
    // Function Call
    checkElementsOnDiagonal(M, N);
}
}
 
// This code is contributed by code_hunt.


Python3
# Python3 program for the above approach
 
# Stores if a number is prime or not
prime = [True]*1000005
 
# Function to generate and store
# primes using Sieve Of Eratosthenes
def SieveOfEratosthenes(N):
   
    # Set all numbers as prime
    # memset(prime, true, sizeof(prime))
    prime[0] = False
    prime[1] = False
 
    for p in range(2, N + 1):
        if p * p > N:
            break
             
        # If p is a prime
        if (prime[p] == True):
 
            # Set all its multiples
            # as non-prime
            for i in range(p * p, N + 1, p):
                prime[i] = False
 
# Function to check if all diagonal
# elements are prime or not
def checkElementsOnDiagonal(M, N):
   
    # Stores if all diagonal
    # elements are prime or not
    flag = 1
 
    # Precompute primes
    SieveOfEratosthenes(1000000)
 
    # Traverse the range [0, N-1]
    for i in range(N):
 
        # Check if numbers on the cross
        # diagonal and main diagonal
        # are primes or not
        flag &= (prime[M[i][i]] and prime[M[i][N - 1 - i]])
 
    # If true, then pr"Yes"
    if (flag):
        print("Yes")
 
    # Otherwise, pr"No"
    else:
        print("No")
 
# Driver Code
if __name__ == '__main__':
    M = [[ 1, 2, 3, 13 ],
        [ 5, 3, 7, 8 ],
        [ 1, 2, 3, 4 ],
        [ 5, 6, 7, 7 ]]
    N = len(M)
 
    # Function Call
    checkElementsOnDiagonal(M, N)
 
    # This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG
{
 
  // Stores if a number is prime or not
  static bool[] prime = new bool[1000005];
 
  // Function to generate and store
  // primes using Sieve Of Eratosthenes
  static void SieveOfEratosthenes(int N)
  {
 
    // Set all numbers as prime
    Array.Fill(prime, true);
    prime[0] = false;
    prime[1] = false;
    for (int p = 2; p * p <= N; p++) {
 
      // If p is a prime
      if (prime[p] == true) {
 
        // Set all its multiples
        // as non-prime
        for (int i = p * p; i <= N; i += p)
 
          prime[i] = false;
      }
    }
  }
 
  // Function to check if all diagonal
  // elements are prime or not
  static void checkElementsOnDiagonal(int[, ] M, int N)
  {
 
    // Stores if all diagonal
    // elements are prime or not
    int flag = 1;
 
    // Precompute primes
    SieveOfEratosthenes(1000000);
 
    // Traverse the range [0, N-1]
    for (int i = 0; i < N; i++) {
 
      // Check if numbers on the cross
      // diagonal and main diagonal
      // are primes or not
      bool flg = (bool)(prime[M[i, i]]
                        && prime[M[i, N - 1 - i]]);
      int val = (flg) ? 1 : 0;
      flag &= val;
    }
 
    // If true, then print "Yes"
    if (flag != 0)
      Console.Write("Yes");
 
    // Otherwise, print "No"
    else
      Console.Write("No");
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    int[, ] M = { { 1, 2, 3, 13 },
                 { 5, 3, 7, 8 },
                 { 1, 2, 3, 4 },
                 { 5, 6, 7, 7 } };
    int N = M.GetLength(0);
 
    // Function Call
    checkElementsOnDiagonal(M, N);
  }
}
 
// This code is ccontributed by ukasp.


Javascript


输出
No

时间复杂度: O(N*log (log N))
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live