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

📅  最后修改于: 2021-09-06 05:37:24             🧑  作者: Mango

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

例子:

天真的方法:

  1. 遍历给定的矩阵并检查当前元素是否属于主对角线。
  2. 如果元素属于主对角线并且它是素数,则将该元素的值添加到 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


Javascript


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


Javascript


输出:
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

蟒蛇3

# 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

Javascript


输出:
3

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

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