Showing posts with label prime number. Show all posts
Showing posts with label prime number. Show all posts

Friday, March 23, 2012

First post and first code. Primefinder

The first post on this blog. I have previously used math packages, namely MATLAB, to solve chemical engineering problems. In an attempt to move away from commercial products and gain a better understanding of what is going on behind the curtain; I've decided to learn how to use python to solve these problems. I'm posting the code as I'm learning. In the beginning it will be mostly python examples but I hope I soon can get in to solve real problems.

This code example generates all prime numbers within a given range. It is a good python example with uses: if statements, for loops, while loops, and user inputs. I know the code can be optimized but I leave it to you. The code is licensed under GNU GPLv3.

Copy the code and save it to a file named primefinder.py and run.

The Code:

#!/usr/bin/env python

print 'This program finds all prime numbers between a range given'
nMin = eval(raw_input('Enter left hand side of the range: '))
nMax = eval(raw_input('Enter right hand side, number is excluded: '))

# Checking if nMin is to small for this algorithm
if nMin <= 2: # If less than 2, add to and start with 3
 a = [2] 
 print '2' 
 nMin = 3
else:
 a = []

i = 2
# Loop to find all primes in the range
for n in range(nMin,nMax):
 while i < n:   # For every number less than n:
  if n%i != 0:  # If n is not a factor of i
   prime = 1 # Set the checking variable to true
   i = i +1  # Go to next number
  else: 
   prime = 0 # Otherwise set checking variable to false
   i = n + 1 # Exit the loop
 i = 2     # Reset i for next number in the range
 # Print the primes found and save them in variable a 
 if prime == 1:
  print n 
  a.append(n)

# Find out how many was found and print result
Size = len(a)
print 'The number of prime numbers found in this range is', Size

# Ask user what to do next.
while 1>0:
 print 'Would you like me to reprint all the numbers?'
 ANS = raw_input('yes/no: ')
 if ANS == 'yes':
  print a
  exit()
 elif ANS == 'no':
  exit()
 else:
  print 'Type yes or no'

An example of the code running:


This program finds all prime numbers between a range given
Enter left hand side of the range: 0
Enter right hand side, number is excluded: 50
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
The number of prime numbers found in this range is 15
Would you like me to reprint all the numbers?
yes/no: yes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]