Welcome, guest | Sign In | My Account | Store | Cart

This is a simple prime number generator in python that I put together for an article I wrote How To Find Prime Numbers In Python. In this one we cut the numbers in half so it is only slightly more efficient than the simplest prime number generator.

Note: There are more efficient ways to do this. Please look at my other recipes.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import sys

def is_prime(num):
	for j in range(2,num):
		if (num % j) == 0: 
			return False
	return True

def main(argv):

	if (len(sys.argv) != 3):
		sys.exit('Usage: prime_numbers2.py <lowest_bound> <upper_bound>')

	low = int(sys.argv[1])
	high = int(sys.argv[2])
	
	if (low == 2):
		print 2, 
	
	if (low % 2 == 0):
		low += 1
		
	for i in range(low,high,2):
		if is_prime(i): 
			print i, 
		
if __name__ == "__main__":
	main(sys.argv[1:])