📜  素数矩阵中主要对角元素的总和

📅  最后修改于: 2021-04-29 17:05:44             🧑  作者: Mango

给定R行和C列的矩阵mat [] [] 。任务是从主对角线中找到所有素数的元素之和。
注意:主要对角线是从矩阵左上角到右下角的对角线。

例子:

天真的方法:

  1. 遍历给定的矩阵,并检查当前元素是否属于主对角线。
  2. 如果element属于主对角线并且它是质数,则将该元素的值加到totalSum中。
  3. 之后,遍历矩阵将打印totalSum的值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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;
}


Java
// Java program for the above approach
class GFG{
 
// Function checks whether a number
// is prime or not
static boolean 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
static 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][j];
           
          // If element belongs to main
          // diagonal and is prime
          if ((i == j) && isPrime(temp))
              totalSum += (temp);
       }
    }
 
    // Print the total sum
    System.out.print(totalSum + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int mat[][] = { { 1, 2, 3, 4, 2 },
                    { 0, 3, 2, 3, 9 },
                    { 0, 4, 1, 2, 8 },
                    { 1, 2, 3, 6, 6 } };
 
    // Function Call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function checks whether a number
# is prime or not
def isPrime(n):
 
    if (n < 2):
        return False
  
    # Iterate to check primarility of n
    for i in range(2, n):
        if (n % i == 0):
            return False
  
    return True
 
# Function calculates the sum of
# prime elements of main diagonal
def primeDiagonalElementSum(mat, r, c):
  
    # Initialise total sum as 0
    totalSum = 0;
  
    # Iterate the given matrix mat[][]
    for i in range(r):
        for j in range(c):
            temp = mat[i][j]
  
            # If element belongs to main
            # diagonal and is prime
            if ((i == j) and isPrime(temp)):
                totalSum += (temp)
  
    # Print the total sum
    print(totalSum)
 
# Driver code
if __name__=="__main__":
     
    R = 4
    C = 5
  
    # Given Matrix
    mat = [ [ 1, 2, 3, 4, 2 ],
            [ 0, 3, 2, 3, 9 ],
            [ 0, 4, 1, 2, 8 ],
            [ 1, 2, 3, 6, 6 ] ]
  
    # Function call
    primeDiagonalElementSum(mat, R, C)
     
# This code is contributed by rutvik_56


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function checks whether a number
// is prime or not
public static 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
public static 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, j];
           
          // If element belongs to main
          // diagonal and is prime
          if ((i == j) && isPrime(temp))
              totalSum += (temp);
       }
    }
 
    // Print the total sum
    Console.WriteLine(totalSum);
}
 
// Driver Code
public static void Main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int [,]mat = { { 1, 2, 3, 4, 2 },
                   { 0, 3, 2, 3, 9 },
                   { 0, 4, 1, 2, 8 },
                   { 1, 2, 3, 6, 6 } };
 
    // Function Call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by SoumikMondal


C++
// C++ program for the above approach
#include 
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;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function checks whether a number
// is prime or not
static boolean 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
static 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][j];
 
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
 
    // Print the total sum
    System.out.print(totalSum + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int mat[][] = { { 1, 2, 3, 4, 2 },
                    { 0, 3, 2, 3, 9 },
                    { 0, 4, 1, 2, 8 },
                    { 1, 2, 3, 6, 6 } };
 
    // Function call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function checks whether a number
# is prime or not
def isPrime(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 or n % 3 == 0):
        return False
         
    i = 5
    while i * i <= n:
        if (n % i == 0 or n % (i + 2) == 0):
            return False
             
        i += 6
         
    return True
 
# Function calculates the sum of
# prime elements of main diagonal
def primeDiagonalElementSum(mat, r, c):
 
    # Initialise total sum as 0
    totalSum = 0
 
    # Iterate the given matrix mat[][]
    for i in range(r):
        for j in range(c):
            temp = mat[i][j]
             
            # If element belongs to main
            # diagonal and is prime
            if ((i == j) and isPrime(temp)):
                totalSum += (temp)
 
    # Print the total sum
    print(totalSum)
     
# Driver Code
R, C = 4, 5
 
# Given Matrix
mat = [ [ 1, 2, 3, 4, 2 ],
        [ 0, 3, 2, 3, 9 ],
        [ 0, 4, 1, 2, 8 ],
        [ 1, 2, 3, 6, 6 ] ]
 
# Function Call
primeDiagonalElementSum(mat, R, C)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
class GFG{
 
// Function checks whether a number
// is prime or not
static 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
static 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,j];
 
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
 
    // Print the total sum
    Console.Write(totalSum + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int [,]mat = { { 1, 2, 3, 4, 2 },
                    { 0, 3, 2, 3, 9 },
                    { 0, 4, 1, 2, 8 },
                    { 1, 2, 3, 6, 6 } };
 
    // Function call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by Rohit_ranjan


输出:
3

时间复杂度: O(R * C * K) ,其中K是矩阵中的最大元素。
辅助空间: O(1)

高效方法:我们可以通过优化数字的原始性测试来优化天真的方法。以下是优化原始性测试的步骤:

  1. 而不是检查,直到N个,我们可以检查,直到开方(N)作为N大要素必须小于因子的倍数已经被选中。
  2. 通过观察除2和3以外的所有素数都为6k±1的形式,可以进一步改进算法。这是因为对于某些整数k以及对于i =-,所有整数都可以表示为(6k + i) 。 1、0、1、2、3或4。
  3. 2分(6k + 0),(6k + 2),(6k + 4);和3除法(6k + 3)。因此,一种更有效的方法是测试N是否可被23整除,然后检查形式为6k±1的所有数字。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
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;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function checks whether a number
// is prime or not
static boolean 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
static 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][j];
 
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
 
    // Print the total sum
    System.out.print(totalSum + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int mat[][] = { { 1, 2, 3, 4, 2 },
                    { 0, 3, 2, 3, 9 },
                    { 0, 4, 1, 2, 8 },
                    { 1, 2, 3, 6, 6 } };
 
    // Function call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python3 program for the above approach
 
# Function checks whether a number
# is prime or not
def isPrime(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 or n % 3 == 0):
        return False
         
    i = 5
    while i * i <= n:
        if (n % i == 0 or n % (i + 2) == 0):
            return False
             
        i += 6
         
    return True
 
# Function calculates the sum of
# prime elements of main diagonal
def primeDiagonalElementSum(mat, r, c):
 
    # Initialise total sum as 0
    totalSum = 0
 
    # Iterate the given matrix mat[][]
    for i in range(r):
        for j in range(c):
            temp = mat[i][j]
             
            # If element belongs to main
            # diagonal and is prime
            if ((i == j) and isPrime(temp)):
                totalSum += (temp)
 
    # Print the total sum
    print(totalSum)
     
# Driver Code
R, C = 4, 5
 
# Given Matrix
mat = [ [ 1, 2, 3, 4, 2 ],
        [ 0, 3, 2, 3, 9 ],
        [ 0, 4, 1, 2, 8 ],
        [ 1, 2, 3, 6, 6 ] ]
 
# Function Call
primeDiagonalElementSum(mat, R, C)
 
# This code is contributed by divyeshrabadiya07

C#

// C# program for the above approach
using System;
class GFG{
 
// Function checks whether a number
// is prime or not
static 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
static 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,j];
 
            // If element belongs to main
            // diagonal and is prime
            if ((i == j) && isPrime(temp))
                totalSum += (temp);
        }
    }
 
    // Print the total sum
    Console.Write(totalSum + "\n");
}
 
// Driver Code
public static void Main(String[] args)
{
    int R = 4, C = 5;
 
    // Given Matrix
    int [,]mat = { { 1, 2, 3, 4, 2 },
                    { 0, 3, 2, 3, 9 },
                    { 0, 4, 1, 2, 8 },
                    { 1, 2, 3, 6, 6 } };
 
    // Function call
    primeDiagonalElementSum(mat, R, C);
}
}
 
// This code is contributed by Rohit_ranjan
输出:
3

时间复杂度: O(R * C * sqrt(K)) ,其中K是矩阵中的最大元素。
辅助空间: O(1)