📜  Prime Fibonnaci | TCS Mockvita 2020(1)

📅  最后修改于: 2023-12-03 15:33:47.416000             🧑  作者: Mango

Prime Fibonacci | TCS Mockvita 2020

Introduction

This problem is a part of the TCS Mockvita 2020. The problem statement requires you to find the nth prime number in the Fibonacci series. To solve this problem, you need both knowledge of prime numbers and Fibonnaci numbers.

Problem Statement

Given a number n, find the nth prime number in the Fibonacci series.

Example
Input: n = 3
Output: 5

Input: n = 5
Output: 13
Approach

To solve this problem, we need to follow the following steps:

  1. Generate the Fibonacci series up to n numbers.
  2. Extract only the prime numbers from the Fibonacci series.
  3. Get the nth prime number from the prime numbers list.

Below is the implementation of the above approach:

def fibonacci(n):
    # Initialization of first two Fibonacci numbers
    fib = [0, 1]
    # Calculate and append the rest of the Fibonacci numbers
    for i in range(2, n):
        fib.append(fib[i-1] + fib[i-2])
    return fib

def check_prime(num):
    # If less than 2, return False as 1 and 0 are not prime
    if num < 2:
        return False
    # Iterate from 2 to num-1, checking if there is a factor
    for i in range(2, num):
        if num % i == 0:
            return False
    return True

def nth_prime_fibonacci(n):
    # Generate the Fibonacci series up to n numbers
    fib_series = fibonacci(n)
    # Extract only the prime numbers from the Fibonacci series
    primes = [num for num in fib_series if check_prime(num)]
    # Get the nth prime number from the prime numbers list
    return primes[n-1]
Time and Space Complexity
  • Time Complexity: O(n^2), where n is the input number
  • Space Complexity: O(n), where n is the input number
Conclusion

The problem requires knowledge of prime numbers and Fibonacci series to find the nth prime number in the Fibonacci series. The approach mentioned above involves generating the Fibonacci series, extracting prime numbers, and getting the nth prime number from the list. The time and space complexities of the solution are also discussed.