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

Twin Primes

Find twin-prime pairs with a fixed Python search. Students check both p and p plus two and understand the candidate bound and one-way pair generation.

AdvancedPhase 6 - Category 3: Loop & Conditional MixExample 4 of 10
twin-primes.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# Find twin primes
11print("Twin primes up to 100:")
12for num in range(3, 101):
13 if is_prime(num) and is_prime(num + 2):
14 print(f"({num}, {num + 2})", end=" ")
15print()

Output

Twin primes up to 100:
(3, 5) (5, 7) (11, 13) (17, 19) (29, 31) (41, 43) (59, 61) (71, 73)

In this one

  • Test related candidates
  • Compose two prime checks
  • Generate each pair once

How it works

  1. 1

    Visit starting values three through one hundred.

  2. 2

    Test num and num + 2 for primality.

  3. 3

    Print the pair only when both pass.

Edge cases

Does (3, 5) qualify?

Does (3, 5) qualify?

Yes. Both values are prime and differ by two.

Does (7, 9) qualify?

Does (7, 9) qualify?

No. Nine is composite.

What's going on

For each num, the code checks primality of num and num + 2. Both must pass before the pair prints.

Beginning at three includes (3, 5), and increasing num generates each oriented pair once. The loop checks starting candidates through one hundred; for this exact bound no qualifying pair extends past it. The helper uses trial division, not a precomputed prime table.

Does (3, 5) qualify? Yes. Both values are prime and differ by two.

Does (7, 9) qualify? No. Nine is composite.

Quiz

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

Question 1

What gap defines the pair here?

Pick an answer to check it.

Question 2

Does (3, 5) qualify?

Pick an answer to check it.

Questions people ask

Does (3, 5) qualify?

Yes. Both values are prime and differ by two.

Does (7, 9) qualify?

No. Nine is composite.

What gap defines the pair here?

Two.