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.
1# Helper function2def is_prime(n):3 if n < 2:4 return False5 for i in range(2, int(n ** 0.5) + 1):6 if n % i == 0:7 return False8 return True910# Generate Fibonacci and check prime11print("Fibonacci primes:")12a, b = 0, 113count = 014while count < 20:15 if a > 1 and is_prime(a):16 print(a, end=" ")17 count += 118 a, b = b, a + b19print()
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
Check the current Fibonacci term for primality.
- 2
Print and increment count only on a prime match.
- 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.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum