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

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

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

例子:

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

  1. 由于组合一对数字可能的最高数字是 99,因此预先计算并存储所有质数 99 使用 Eratosthenes 筛并将其存储在一个布尔数组中,比如prime[] ,其中prime[i] = 0 (非素数)和1 (素数)。
  2. 遍历数组Q[],执行以下步骤:
    • 通过执行Q[i] % 10提取Q[i]的最后一位数字并将其存储在变量中,例如last
    • 通过连续地将Q [I]10直到Q [I]中提取Q [I]的第一个数字降低大于10至小于并将其存储在一个变量,表示第一个
    • 现在,生成两种可能的组合:
      • 第一个 * 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)

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