Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Fibonacci Prime Numbers

Search Fibonacci terms for prime values with Python. Students trace pair updates and learn why twenty prime matches can require far more than twenty terms.

AdvancedPhase 6 - Category 1: Number LogicExample 7 of 10
fibonacci-prime-numbers.py
1# Helper function
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10# Generate Fibonacci and check prime
11print("Fibonacci primes:")
12a, b = 0, 1
13count = 0
14while count < 20:
15 if a > 1 and is_prime(a):
16 print(a, end=" ")
17 count += 1
18 a, b = b, a + b
19print()

Output

...

The sample abbreviates a longer result. The program prints the intervening values; it does not print these dots.

In this one

  • Advance Fibonacci state
  • Count matching terms only
  • Recognize impractical trial division

How it works

  1. 1

    Check the current Fibonacci term for primality.

  2. 2

    Print and increment count only on a prime match.

  3. 3

    Advance the pair and continue until twenty matches.

Edge cases

Does the loop stop after twenty terms?

Does the loop stop after twenty terms?

No. It stops after twenty prime matches.

Does a value of one count?

Does a value of one count?

No. The explicit guard and helper reject it.

What's going on

a and b hold consecutive Fibonacci terms. The loop checks a, then updates the pair to b and a + b.

count increases only when a prime term is printed. The target is twenty prime matches, not twenty terms; this can require enormous trial-division work and may not finish in a practical classroom session. The displayed ellipsis is only a partial output preview, not text printed by the code.

Does the loop stop after twenty terms? No. It stops after twenty prime matches.

Does a value of one count? No. The explicit guard and helper reject it.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why can this run for a very long time?

Pick an answer to check it.

Question 2

Does the loop stop after twenty terms?

Pick an answer to check it.

Questions people ask

Does the loop stop after twenty terms?

No. It stops after twenty prime matches.

Does a value of one count?

No. The explicit guard and helper reject it.

Why can this run for a very long time?

Later Fibonacci values become huge and trial division is expensive.