Python Outputting Primes in a Range
A prime number, also called a prime, is infinite in number. It is not divisible by any divisor other than 1 and itself.
The following example outputs prime numbers in a specified range:
Example (Python 3.0+)
#!/usr/bin/python3
Output the prime numbers in a specified range
take input from the user
lower
=
int
(
input
(
"
Enter the minimum value of the range:
"
)
)
upper
=
int
(
input
(
"
Enter the maximum value of the range:
"
)
)
for
num
in
range
(
lower
,
upper
1
)
:
A prime number is greater than 1
if
num
1
:
for
i
in
range
(
2
,
num
)
:
if
(
num
%
i
)
==
0
:
break
else
:
(
num
)
Running the above program, the output is:
$ python3 test.py
输入区间最小值: 1
输入区间最大值: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
Use trial division
Trial division is a basic algorithm that performs division tests on each number to determine whether it is prime. The following is code that uses trial division to output prime numbers in a specified range:
Example
def
is_prime
(
n
)
:
"""Determine whether a number is prime"""
if
n
<=
1
:
return
False
if
n
<=
3
:
return
True
if
n %
2
==
0
or
n %
3
==
0
:
return
False
i
=
5
while
i * i
<=
n:
if
n % i
==
0
or
n %
(
i +
2
)
==
0
:
return
False
i +
=
6
return
True
def
primes_in_range
(
start
,
end
)
:
"""Output prime numbers in a specified range"""
for
num
in
range
(
start
,
end +
1
)
:
if
is_prime
(
num
)
:
(
num
)
Example: output prime numbers in the range 10 to 50
primes_in_range
(
10
,
50
)
Use the Sieve of Eratosthenes
The Sieve of Eratosthenes is a more efficient algorithm, especially suitable for finding prime numbers in a large range. The following is code that uses the Sieve of Eratosthenes to output prime numbers in a specified range:
Example
def
sieve_of_eratosthenes
(
max_num
)
:
"""Use the Sieve of Eratosthenes to find all primes up to max_num"""
sieve
=
[
True
]
(
max_num +
1
)
sieve
[
0
]
=
sieve
[
1
]
=
False
0 and 1 are not prime numbers
p
=
2
while
p * p
<=
max_num:
if
sieve
[
p
]
:
for
multiple
in
range
(
p * p
,
max_num +
1
,
p
)
:
sieve
[
multiple
]
=
False
p +
=
1
return
[
p
for
p
,
is_prime
in
enumerate
(
sieve
)
if
is_prime
]
def
primes_in_range
(
start
,
end
)
:
"""Output prime numbers in a specified range"""
primes
=
sieve_of_eratosthenes
(
end
)
for
num
in
primes:
if
num
=
start:
(
num
)
Example: output prime numbers in the range 10 to 50
primes_in_range
(
10
,
50
)
Python3 Examples