301. Python Program to Find Twin Primes in a Range
HardPhase 3 · Challenge
It takes a few steps, and you know every tool it uses: nested for loops, break, a list and the in operator. Find the pairs from 1 to 20 on paper first.
Overview
A prime number is a whole number of 2 or more that divides evenly only by 1 and by itself, like 2, 3, 5 and 7. Prime puzzles are common in interviews, because they mix loops, flags and lists.
Problem Statement
Emeka runs a number club, and this week's topic is twin primes. Twin primes are two primes that differ by exactly 2. For example, 11 and 13 are twin primes. 7 and 11 are not, because they differ by 4.
Read a start number and an end number. Print every pair of twin primes where both numbers are from the start to the end. The start and the end count too.
- Print each pair on its own line, in the format
11 and 13, with the smaller number first. - Print the pairs from the smallest to the largest.
- A number can be in two pairs: 3 and 5, then 5 and 7.
- If there are no pairs, print only
No twin primes.
Examples
Example 1. Input:
1
20
gives:
3 and 5
5 and 7
11 and 13
17 and 19
Why: the primes from 1 to 20 are 2, 3, 5, 7, 11, 13, 17 and 19. Only these four pairs differ by 2. 1 is not a prime.
Example 2. Input:
20
40
gives:
29 and 31
Why: the primes from 20 to 40 are 23, 29, 31 and 37. Only 29 and 31 differ by 2.
Input
Two lines:
- The start: a whole number (1 or more).
- The end: a whole number, from the start up to 1000.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each pair, or the single line No twin primes. A pair counts only when both of its numbers are inside the range. The tests try 8 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.