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

This is a prime number generator in python that I put together for an article I wrote How To Find Prime Numbers In Python. The script will generate a prime number of x digits, where x is less than 15. It might work for larger x, but it will take a while.

Python, 34 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
29
30
31
32
33
34
import sys
import math 
import random

def is_prime(num):
	for j in range(2,int(math.sqrt(num)+1)):
		if (num % j) == 0: 
			return False
	return True

def main(argv):

	if (len(sys.argv) != 2):
		sys.exit('Usage: prime_numbers6.py <num_digits>')


	digits = int(sys.argv[1])
	low = int('1' + '0' * (digits-1))
	high = int('9' * digits)
	done = False	
			
	if (low == 1):
		low = 2
			
	while not done:
		num = random.randint(low,high)
		if is_prime(num): 
			print 'A random ' + str(digits) + ' prime number is: ' + str(num)
			done = True
			
	
		
if __name__ == "__main__":
	main(sys.argv[1:])