📌  相关文章
📜  检查每个数组元素的首位和最后一位数字的连接是否形成质数

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

给定的阵列Q []N个整数的,对阵列Q []中的每个元素的任务是检查任何数字,通过连接第一和Q [I]的最后一位数字形成的是否为素数或不是。

例子:

方法:使用Eratosthenes筛可以有效地解决问题请按照以下步骤解决给定的问题:

  1. 由于通过组合一对数字而可能获得的最大数字是99,因此预先计算并存储所有素数直到 99使用Eratosthenes的Sieve并将其存储在一个布尔数组中,例如prime [] ,其中prime [i] = 0 (非素数)和1 (素数)。
  2. 遍历数组Q [],并执行以下步骤:
    • 通过执行Q [i]%10来提取Q [i]的最后一位,并将其存储在变量中,例如last
    • 通过将Q [i]连续除以10直到Q [i]减小到小于10来提取Q [i]的第一位数,并将其存储在变量中,例如first
    • 现在,生成两个可能的组合:
      • 前* 10 +最后
      • 最后* 10 +首先
    • 对于上述两个组合中的每一个,请检查它们是否为质数。
    • 如果发现形成的任何数字均为质数,则打印True,否则打印False。

下面是上述方法的实现。

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Stores if i is prime (1)
// or non-prime(0)
int sieve[105];
 
// Function to build sieve array
void buildSieve()
{
    // Inititalize all the values
    // in sieve equals to 1
    for (int i = 2; i < 100; i++)
        sieve[i] = 1;
 
    // Sieve of Eratosthenes
    for (int i = 2; i < 100; i++) {
 
        // If current number is prime
        if (sieve[i] == 1) {
 
            // Set all multiples as non-prime
            for (int j = i * i; j < 100; j += i)
                sieve[j] = 0;
        }
    }
}
 
// Function to check if the numbers formed
// by combining first and last digits
// generates a prime number or not
bool isAnyPrime(int first, int last)
{
    int num1 = first * 10 + last;
    int num2 = last * 10 + first;
 
    // Check if any of the numbers
    // formed is a prime number or not
    if (sieve[num1] == 1 || sieve[num2] == 1)
        return true;
    else
        return false;
}
 
void performQueries(vector q)
{
 
    // Traverse the array of queries
    for (int i = 0; i < q.size(); i++) {
        int A = q[i];
 
        // Extract the last digit
        int last = A % 10;
 
        // Extract the first digit
        int first;
        while (A >= 10)
            A = A / 10;
        first = A;
 
        // If any of the two
        // numbers is prime
        if (isAnyPrime(first, last))
            cout << "True\n";
 
        // Otherwise
        else
            cout << "False\n";
    }
}
 
// Driver Code
int main()
{
    vector q = { 30, 66 };
 
    // Computes and stores
    // primes using Sieve
    buildSieve();
 
    // Function call to perform queries
    performQueries(q);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG
{
 
// Stores if i is prime (1)
// or non-prime(0)
static int[] sieve = new int[105];
 
// Function to build sieve array
static void buildSieve()
{
   
    // Inititalize all the values
    // in sieve equals to 1
    for (int i = 2; i < 100; i++)
        sieve[i] = 1;
 
    // Sieve of Eratosthenes
    for (int i = 2; i < 100; i++) {
 
        // If current number is prime
        if (sieve[i] == 1) {
 
            // Set all multiples as non-prime
            for (int j = i * i; j < 100; j += i)
                sieve[j] = 0;
        }
    }
}
 
// Function to check if the numbers formed
// by combining first and last digits
// generates a prime number or not
static boolean isAnyPrime(int first, int last)
{
    int num1 = first * 10 + last;
    int num2 = last * 10 + first;
 
    // Check if any of the numbers
    // formed is a prime number or not
    if (sieve[num1] == 1 || sieve[num2] == 1)
        return true;
    else
        return false;
}
 
static void performQueries(int[] q)
{
 
    // Traverse the array of queries
    for (int i = 0; i < q.length; i++) {
        int A = q[i];
 
        // Extract the last digit
        int last = A % 10;
 
        // Extract the first digit
        int first;
        while (A >= 10)
            A = A / 10;
        first = A;
 
        // If any of the two
        // numbers is prime
        if (isAnyPrime(first, last))
            System.out.println("True\n");
 
        // Otherwise
        else
            System.out.print("False\n");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int[] q = { 30, 66 };
 
    // Computes and stores
    // primes using Sieve
    buildSieve();
 
    // Function call to perform queries
    performQueries(q);
}
}
 
// This code is contributed by susmitakundugoaldanga.


Python3
# Python 3 program for the above approach
 
# Stores if i is prime (1)
# or non-prime(0)
sieve = [0 for i in range(105)]
 
# Function to build sieve array
def buildSieve():
    global sieve
     
    # Inititalize all the values
    # in sieve equals to 1
    for i in range(2, 100):
        sieve[i] = 1
 
    # Sieve of Eratosthenes
    for i in range(2, 100):
       
        # If current number is prime
        if (sieve[i] == 1):
           
            # Set all multiples as non-prime
            for j in range( i* i, 100, i):
                sieve[j] = 0
 
# Function to check if the numbers formed
# by combining first and last digits
# generates a prime number or not
def isAnyPrime(first, last):
    global sieve
    num1 = first * 10 + last
    num2 = last * 10 + first
 
    # Check if any of the numbers
    # formed is a prime number or not
    if (sieve[num1] == 1 or sieve[num2] == 1):
        return True
    else:
        return False
 
def performQueries(q):
   
    # Traverse the array of queries
    for i in range(len(q)):
        A = q[i]
 
        # Extract the last digit
        last = A % 10
 
        # Extract the first digit
        first = 0
        while (A >= 10):
            A = A // 10
        first = A
 
        # If any of the two
        # numbers is prime
        if (isAnyPrime(first, last)):
            print("True")
 
        # Otherwise
        else:
            print("False")
 
# Driver Code
if __name__ == '__main__':
    q =  [30, 66]
 
    # Computes and stores
    # primes using Sieve
    buildSieve()
 
    # Function call to perform queries
    performQueries(q)
     
    # This code is contributed by bgangwar59.


C#
// C# program for above approach
/*package whatever //do not write package name here */
using System;
public class GFG
{
   
// Stores if i is prime (1)
// or non-prime(0)
static int[] sieve = new int[105];
 
// Function to build sieve array
static void buildSieve()
{
   
    // Inititalize all the values
    // in sieve equals to 1
    for (int i = 2; i < 100; i++)
        sieve[i] = 1;
 
    // Sieve of Eratosthenes
    for (int i = 2; i < 100; i++)
    {
 
        // If current number is prime
        if (sieve[i] == 1)
        {
 
            // Set all multiples as non-prime
            for (int j = i * i; j < 100; j += i)
                sieve[j] = 0;
        }
    }
}
 
// Function to check if the numbers formed
// by combining first and last digits
// generates a prime number or not
static bool isAnyPrime(int first, int last)
{
    int num1 = first * 10 + last;
    int num2 = last * 10 + first;
 
    // Check if any of the numbers
    // formed is a prime number or not
    if (sieve[num1] == 1 || sieve[num2] == 1)
        return true;
    else
        return false;
}
 
static void performQueries(int[] q)
{
 
    // Traverse the array of queries
    for (int i = 0; i < q.Length; i++) {
        int A = q[i];
 
        // Extract the last digit
        int last = A % 10;
 
        // Extract the first digit
        int first;
        while (A >= 10)
            A = A / 10;
        first = A;
 
        // If any of the two
        // numbers is prime
        if (isAnyPrime(first, last))
            Console.Write("True\n");
 
        // Otherwise
        else
            Console.Write("False\n");
    }
}
 
// Driver code
public static void Main(String[] args)
{
    int[] q = { 30, 66 };
 
    // Computes and stores
    // primes using Sieve
    buildSieve();
 
    // Function call to perform queries
    performQueries(q);
}
}
 
// This code is contributed by code_hunt.


Javascript


输出:
True
False

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