Home / Python Language / List Fibonacci numbers that are less than n and are prime

List Fibonacci numbers that are less than n and are prime

Task 1

Python Exercise: Write a program to list Fibonacci numbers less than n that are prime numbers in Python. N is a positive integer entered from the keyboard.

Solution

import math
 
"""
 * Calculate the nth fibonacci number
 *
 * @param n: index of fibonacci number starting from 0
 * eg: F0 = 0, F1 = 1, F2 = 1, F3 = 2
 * @return the nth fibonacci number
"""
def fibonacci(n):
    if (n < 0):
        return -1;
    elif (n == 0 or n == 1):
        return n;
    else:
        return fibonacci(n - 1) + fibonacci(n - 2);
 
 
"""
 * check the original number
 * 
 * @author viettuts.vn
 * @param n: number of Nguyen Duong
 * @return true is the original number, 
 * false is not a large number
"""
def isPrimeNumber(n):
    # raw number n < 2 is not a large raw number
    if (n < 2):
        return False;
 
    # check original number when n >= 2
    squareRoot = int(math.sqrt(n));
    for i in range(2, squareRoot + 1):
        if (n % i == 0):
            return False;
    return True;
 
 
"""
 * The program lists Fibonacci numbers smaller than n as prime numbers.
 * With n entered from the keyboard.
 *  
 * @author viettuts.vn
"""
n = int(input("Enter positive integer n = "));
print("All fibonacci numbers less than", n, "and prime:");
i = 0;
fin = fibonacci(i);
while(fin < n):
    fin = fibonacci(i);
    if (isPrimeNumber(fin)):
        print(fin)
    i = i + 1;

Result:

Enter positive integer n = 100
All fibonacci numbers less than 100 and prime:
2
3
5
13
89

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖