📜  通过在给定范围内连接成对的素数形成的斐波那契素数系列的N项

📅  最后修改于: 2021-04-23 08:16:09             🧑  作者: Mango

给定两个整数XY ,任务是执行以下操作:

  • 找出[X,Y]范围内的所有素数。
  • 通过组合给定范围内的每对素数生成所有可能的数字。
  • 在上面生成的所有可能的数字中找到质数。计算其中素数的数量,以N表示
  • 打印斐波那契数列的N项,该数列是由上述列表中最小和最大的素数组成的,作为该序列的前两个项。

例子:

方法:
请按照以下步骤解决问题:

  • 使用Eratothenes筛产生所有可能的质数。
  • 遍历范围[X,Y]并借助上一步中生成的primes []数组生成该范围内的所有素数。
  • 遍历素数列表并从列表中生成所有可能的对。
  • 对于每对,将两个素数连接起来,然后检查它们的串联是否为素数。
  • 找出所有此类素数的最大值最小值,并对获得的所有此类素数进行计数。
  • 最后,将在上述步骤中获得的最小值最大值的斐波那契数列的计数th打印为该数列的前两项。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
#define int long long int
 
// Stores at each index if it's a
// prime or not
int prime[100001];
 
// Sieve of Eratosthenes to
// generate all possible primes
void SieveOfEratosthenes()
{
    for(int i = 0; i < 100001; i++)
        prime[i] = 1;
         
    int p = 2;
    while (p * p <= 100000)
    {
         
        // If p is a prime
        if (prime[p] == 1)
        {
             
            // Set all multiples of
            // p as non-prime
            for(int i = p * p;
                    i < 100001;
                    i += p)
                prime[i] = 0;
        }    
        p += 1;
    }    
}
     
int join(int a, int b)
{
    int mul = 1;
    int bb = b;
     
    while(b != 0)
    {
        mul *= 10;
        b /= 10;
    }
    a *= mul;
    a += bb;
    return a;
}
 
// Function to generate the
// required Fibonacci Series
void fibonacciOfPrime(int n1, int n2)
{
    SieveOfEratosthenes();
     
    // Stores all primes between
    // n1 and n2
    vectorinitial;
     
    // Generate all primes between
    // n1 and n2
    for(int i = n1; i <= n2; i++)
        if (prime[i])
            initial.push_back(i);
             
    // Stores all concatenations
    // of each pair of primes
    vectornow;
     
    // Generate all concatenations
    // of each pair of primes
    for(auto a:initial)
        for(auto b:initial)
            if (a != b)
            {
                int c = join(a,b);
                now.push_back(c);
            }
                 
                 
    // Stores the primes out of the
    // numbers generated above
    vectorcurrent;
     
    for(auto x:now)
        if (prime[x])
            current.push_back(x);
             
    // Store the unique primes
    setcurrent_set;
    for(auto i:current)
        current_set.insert(i);
     
    // Find the minimum
    int first = *min_element(current_set.begin(),
                             current_set.end());
     
    // Find the minimum
    int second = *max_element(current_set.begin(),
                              current_set.end());
                               
    // Find N
    int count = current_set.size() - 1;
    int curr = 1;
    int c;
     
    while( curr < count)
    {
        c = first + second;
        first = second;
        second = c;
        curr += 1;
    }
     
    // Print the N-th term
    // of the Fibonacci Series
    cout << (c) << endl;
}
     
// Driver Code
int32_t main()
{
    int x = 2;
    int y = 40;
     
    fibonacciOfPrime(x, y);
}
 
// This code is contributed by Stream_Cipher


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Stores at each index if it's a 
// prime or not    
static int prime[] = new int [100001];
 
// Sieve of Eratosthenes to
// generate all possible primes
static void SieveOfEratosthenes()
{
    for(int i = 0; i < 100001; i++)
        prime[i] = 1;
         
    int p = 2;
    while (p * p <= 100000)
    {
         
        // If p is a prime
        if (prime[p] == 1)
        {
             
            // Set all multiples of
            // p as non-prime
            for(int i = p * p;
                    i < 100001;
                    i += p)
                prime[i] = 0;
        }    
        p += 1;
    }    
}
 
static int join(int a,int b)
{
    int mul = 1;
    int bb = b;
     
    while(b != 0)
    {
        mul *= 10;
        b /= 10;
    }
    a *= mul;
    a += bb;
    return a;
}
 
// Function to generate the
// required Fibonacci Series
static void fibonacciOfPrime(int n1, int n2)
{
    SieveOfEratosthenes();
     
    // Stores all primes between
    // n1 and n2
    Vector initial = new Vector<>();
     
    // Generate all primes between
    // n1 and n2
    for(int i = n1; i <= n2; i++)
        if (prime[i] == 1)
            initial.add(i);
             
    // Stores all concatenations
    // of each pair of primes
    Vector now = new Vector<>();
     
    // Generate all concatenations
    // of each pair of primes
    for(int i = 0; i < initial.size(); i++)
    {
        for(int j = 0; j < initial.size(); j++)
        {
            int a = (int)initial.get(i);
            int b = (int)initial.get(j);
             
            if (a != b)
            {
                int c = join(a, b);
                now.add(c);
            }
        }
    }
     
    // Stores the primes out of the
    // numbers generated above
    Vector current = new Vector<>();
     
    for(int i = 0; i < now.size(); i++)
        if (prime[(int)now.get(i)] == 1)
            current.add((int)now.get(i));
             
    // Store the unique primes
    int cnt[] = new int[1000009];
    for(int i = 0; i < 1000001; i++)
        cnt[i] = 0;
         
    Vector current_set = new Vector<>();
    for(int i = 0; i < current.size(); i++)
    {
        cnt[(int)current.get(i)]++;
        if (cnt[(int)current.get(i)] == 1)
            current_set.add((int)current.get(i));
    }
     
    // Find the minimum
    long first = 1000000000;
    for(int i = 0; i < current_set.size(); i++)
        first = Math.min(first,
                         (int)current_set.get(i));
                          
    // Find the minimum
    long second = 0;
    for(int i = 0; i < current_set.size(); i++)
        second = Math.max(second,
                         (int)current_set.get(i));
                          
    // Find N
    int count = current_set.size() - 1;
    long curr = 1;
    long c = 0;
     
    while(curr < count)
    {
        c = first + second;
        first = second;
        second = c;
        curr += 1;
    }
     
    // Print the N-th term
    // of the Fibonacci Series
    System.out.println(c);
}
 
// Driver code
public static void main(String[] args)
{
    int x = 2;
    int y = 40;
     
    fibonacciOfPrime(x, y);
}
}
 
// This code is contributed by Stream_Cipher


Python3
# Python3 Program to implement
# the above approach
 
# Stores at each index if it's a
# prime or not
prime = [True for i in range(100001)]
 
# Sieve of Eratosthenes to
# generate all possible primes
def SieveOfEratosthenes():
     
    p = 2
    while (p * p <= 100000):
         
        # If p is a prime
        if (prime[p] == True):
             
            # Set all multiples of p as non-prime
            for i in range(p * p, 100001, p):
                prime[i] = False
                 
        p += 1
 
# Function to generate the
# required Fibonacci Series
def fibonacciOfPrime(n1, n2):
     
    SieveOfEratosthenes()
     
    # Stores all primes between
    # n1 and n2
    initial = []
     
    # Generate all primes between
    # n1 and n2
    for i in range(n1, n2):
        if prime[i]:
            initial.append(i)
             
    # Stores all concatenations
    # of each pair of primes
    now = []
     
    # Generate all concatenations
    # of each pair of primes
    for a in initial:
        for b in initial:
            if a != b:
                c = str(a) + str(b)
                now.append(int(c))
                 
    # Stores the primes out of the
    # numbers generated above
    current = []
     
    for x in now:
        if prime[x]:
            current.append(x)
             
    # Store the unique primes
    current = set(current)
     
    # Find the minimum
    first = min(current)
     
    # Find the minimum
    second = max(current)
     
    # Find N
    count = len(current) - 1
    curr = 1
     
    while curr < count:
        c = first + second
        first = second
        second = c
        curr += 1
     
    # Print the N-th term
    # of the Fibonacci Series
    print(c)
 
# Driver Code
if __name__ == "__main__":
 
    x = 2
    y = 40
    fibonacciOfPrime(x, y)


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Stores at each index if it's a  
// prime or not     
static int[] prime = new int[100001];
       
// Sieve of Eratosthenes to 
// generate all possible primes
static void SieveOfEratosthenes()
{
  for(int i = 0; i < 100001; i++)
    prime[i] = 1;
 
  int p = 2;
  while (p * p <= 100000)
  {
    // If p is a prime
    if (prime[p] == 1)
    {
      // Set all multiples of
      // p as non-prime
      for(int i = p * p;
              i < 100001; i += p)
        prime[i] = 0;
    }
     
    p += 1;
  }     
}
       
static int join(int a,
                int b)
{
  int mul = 1;
  int bb = b;
 
  while(b != 0)
  {
    mul *= 10;
    b /= 10;
  }
   
  a *= mul;
  a += bb;
  return a;
}
       
// Function to generate the 
// required Fibonacci Series
static void fibonacciOfPrime(int n1,
                             int n2)
{
  SieveOfEratosthenes();
 
  // Stores all primes
  // between n1 and n2
  List initial =
            new List();
 
  // Generate all primes
  // between n1 and n2
  for(int i = n1; i <= n2; i++)
    if (prime[i] == 1)
      initial.Add(i);
 
  // Stores all concatenations
  // of each pair of primes
  List now =
            new List();
 
  // Generate all concatenations
  // of each pair of primes
  for(int i = 0; i < initial.Count; i++)
  {
    for(int j = 0; j < initial.Count; j++)
    {
      int a = initial[i];
      int b = initial[j];
 
      if (a != b)
      {
        int C = join(a, b);
        now.Add(C);
      }
    }
  }
 
  // Stores the primes out of the
  // numbers generated above
  List current =
            new List();
 
  for(int i = 0; i < now.Count; i++)
    if (prime[now[i]] == 1)
      current.Add(now[i]);
 
  // Store the unique primes
  int[] cnt = new int[1000009];
   
  for(int i = 0; i < 1000001; i++)
    cnt[i] = 0;
 
  List current_set =
            new List();
   
  for(int i = 0; i < current.Count; i++)
  {
    cnt[current[i]]++;
     
    if (cnt[current[i]] == 1)
      current_set.Add(current[i]);
  }
 
  // Find the minimum
  long first = 1000000000;
   
  for(int i = 0;
          i < current_set.Count; i++)
    first = Math.Min(first,
                     current_set[i]);
 
  // Find the minimum
  long second = 0;
   
  for(int i = 0;
          i < current_set.Count; i++)
    second = Math.Max(second,
                      current_set[i]);
   
  // Find N
  int count = current_set.Count - 1;
  long curr = 1;
  long c = 0;
 
  while(curr < count)
  {
    c = first + second;
    first = second;
    second = c;
    curr += 1;
  }
 
  // Print the N-th term
  // of the Fibonacci Series
  Console.WriteLine(c);
}
 
// Driver code
static void Main()
{
  int x = 2;
  int y = 40;
  fibonacciOfPrime(x, y);
}
}
 
// This code is contributed by divyeshrabadiya07


输出:
13158006689

时间复杂度: O(N 2 + log(log(maxm))),其中O(N 2 )生成所有对,O(1)检查一个数字是否为质数,maxm为质数的大小[]
辅助空间: O(maxm)