Sunday, 21 April 2013
Python code snippet - Prime Numbers
This is a code snippet for generating prime numbers in Python.
#Prime number Python Example
#---------------------------
# (c) Leonard Aye 2013
#
# Prints the prime numbers between 1- 100.
# A Prime Number is one which is wholly divisible by 1 and itself only.
#For each number i, divide this from no 2 up to i-1 and check that it leaves
#no remainder (since we know that 1 and itself are divisible).
#
for i in range(1,100):
prime = 1
for j in range(2, i-1, 1):
if (i % j == 0):
prime=0 #if any other no is wholly divisible then it's not a prime
break #so break out of the loop.
if prime == 1:
print i
If you know of a more efficient way, then please comment below.
Subscribe to:
Posts (Atom)