在二维数组(矩阵)中查找素数
给定一个二维数组mat[][] ,任务是在这个二维数组中找到并打印素数及其位置(基于 1 的索引)。
例子:
Input: mat[][] = {{1, 2}, {2, 1}}
Output:
1 2 2
2 1 2
Explanation: First prime is at position row 1 and column 2 and the value is 2
Second prime is at position row 2 and column 1 and the value is 2
Input: mat[][] = {{1, 1}, {1, 1}}
Output: -1
Explanation: There is no prime number in this 2d array
朴素方法:基本思想是遍历二维数组,并为每个数字检查它是否为素数。如果它是素数,则打印每个找到的素数的位置和值。
时间复杂度: O(NM*sqrt(X)),其中 N*M 是矩阵的大小,X 是矩阵中的最大元素
辅助空间: O(1)
有效方法:我们可以使用筛子有效地检查数字是否为素数。然后遍历二维数组并简单地检查数字是否在 O(1) 中是素数。
请按照以下步骤实施此方法:
- 从矩阵中找到最大元素并将其存储在变量maxNum中。
- 现在使用 eratosthenes筛找到从1 到 maxNum的素数 并将结果存储在数组prime[]中。
- 现在遍历矩阵并使用prime[]数组检查每个数字是否为素数。
- 对于矩阵中的每个素数,打印其位置(行、列)和值。
下面是上述方法的实现:
C++
// C++ code to implement the above approach
#include
using namespace std;
#define MAXN 100001
bool prime[MAXN];
// Function to find prime numbers using sieve
void SieveOfEratosthenes()
{
int n = MAXN - 1;
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
memset(prime, true, sizeof(prime));
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
void printPrimes(vector >& arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i][j]] == true) {
// Print the position and value
// if found true
cout << i + 1 << " " << j + 1 << " "
<< arr[i][j] << endl;
}
}
}
}
// Driver Code
int main()
{
int N = 2;
vector > arr;
vector temp(N, 2);
temp[0] = 1;
temp[1] = 2;
arr.push_back(temp);
temp[0] = 2;
temp[1] = 1;
arr.push_back(temp);
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
static int MAXN = 100001;
static boolean prime[] = new boolean[MAXN];
// Function to find prime numbers using sieve
static void SieveOfEratosthenes()
{
int n = MAXN - 1;
Arrays.fill(prime, true);
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i = i + p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
static void printPrimes(int[][] arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i][j]] == true) {
// Print the position and value
// if found true
System.out.print((i + 1));
System.out.print(" ");
System.out.print(j + 1);
System.out.print(" ");
System.out.print(arr[i][j]);
System.out.println();
}
}
}
}
// Driver Code
public static void main(String[] args)
{
int N = 2;
int arr[][] = new int[N][N];
arr[0][0] = 1;
arr[0][1] = 2;
arr[1][0] = 2;
arr[1][1] = 1;
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
}
}
// This code is contributed by Potta Lokesh
Python3
# python code to implement the above approach
import math
MAXN = 100001
prime = [True for _ in range(MAXN)]
# Function to find prime numbers using sieve
def SieveOfEratosthenes():
global prime
n = MAXN - 1
# Create a boolean array
# "prime[0..n]" and initialize
# all entries it as true.
# A value in prime[i] will
# finally be false if i is
# Not a prime, else true.
prime[0] = False
prime[1] = False
for p in range(2, int(math.sqrt(n)) + 1):
# If prime[p] is not changed,
# then it is a prime
if (prime[p] == True):
# Update all multiples
# of p greater than or
# equal to the square of it
# numbers which are multiple
# of p and are less than p^2
# are already been marked.
for i in range(p*p, n+1, p):
prime[i] = False
# Function to print the position and
# value of the primes in given matrix
def printPrimes(arr, n):
# Traverse the matrix
for i in range(0, n):
for j in range(0, n):
# Check if the element is prime
# or not in O(1)
if (prime[arr[i][j]] == True):
# Print the position and value
# if found true
print(f"{i + 1} {j + 1} {arr[i][j]}")
# Driver Code
if __name__ == "__main__":
N = 2
arr = []
temp = [2 for _ in range(N)]
temp[0] = 1
temp[1] = 2
arr.append(temp.copy())
temp[0] = 2
temp[1] = 1
arr.append(temp.copy())
# Precomputing prime numbers using sieve
SieveOfEratosthenes()
# Find and print prime numbers
# present in the matrix
printPrimes(arr, N)
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
static int MAXN = 100001;
static bool[] prime = new bool[MAXN];
// Function to find prime numbers using sieve
static void SieveOfEratosthenes()
{
int n = MAXN - 1;
Array.Fill(prime, true);
// Create a boolean array
// "prime[0..n]" and initialize
// all entries it as true.
// A value in prime[i] will
// finally be false if i is
// Not a prime, else true.
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed,
// then it is a prime
if (prime[p] == true) {
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
for (int i = p * p; i <= n; i = i + p)
prime[i] = false;
}
}
}
// Function to print the position and
// value of the primes in given matrix
static void printPrimes(int[,] arr, int n)
{
// Traverse the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Check if the element is prime
// or not in O(1)
if (prime[arr[i,j]] == true) {
// Print the position and value
// if found true
Console.Write((i + 1));
Console.Write(" ");
Console.Write(j + 1);
Console.Write(" ");
Console.Write(arr[i,j]);
Console.WriteLine();
}
}
}
}
// Driver Code
public static void Main(String[] args)
{
int N = 2;
int[,] arr = new int[N,N];
arr[0,0] = 1;
arr[0,1] = 2;
arr[1,0] = 2;
arr[1,1] = 1;
// Precomputing prime numbers using sieve
SieveOfEratosthenes();
// Find and print prime numbers
// present in the matrix
printPrimes(arr, N);
}
}
// This code is contributed by Saurabh Jaiswal
Javascript
输出
1 2 2
2 1 2
时间复杂度: O(N*M),其中 N*M 是矩阵的大小。
辅助空间: O(maxNum),其中 maxNum 是矩阵中的最大元素。