473,503 Members | 1,654 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Crashing prime number calculator

22 New Member
Well, I've been picking at learning python, got tired of reading, and figured I'd try to replicate my prime number generator I wrote (with much TSDN forum help) in C++. I've hit a stumbling block... the program is supposed to print onscreen all the prime numbers between two numbers given to it, so if I put in 1 and 10, it should print out 1, 3, 5, 7 (I know, technically 1 isn't considered prime, and 2 should be on there, but otherwise...) Which it does, but then IDLE freezes and needs to be killed with system monitor (in ubuntu 6.06)... If it helps, I am using Python v. 2.4.3

And the code:
Expand|Select|Wrap|Line Numbers
  1. print
  2. print
  3. print "This program identifies all the prime numbers"
  4. print "between two given numbers"
  5. print
  6.  
  7. # I just wanted the start function to take two integers
  8. # and pass them to prime_test, with num1 as testnum and
  9. # num2 as maxnum.
  10. def start():
  11.     num1 = input("Please enter the lower number: ")
  12.     num2 = input("Please enter the higher number: ")
  13.     if num1 > num2:
  14.         print "Please input the lower number first."
  15.         start()
  16.     elif num1 == num2:
  17.         print "Please use 2 different numbers."
  18.         start()
  19.     elif (num1 < 0) or (num2 < 0):
  20.         print "Please use positive integers only please."
  21.         start()
  22.     prime_test(num1, num2)
  23.  
  24.  
  25. # I'm not sure where the problem is, but I think it
  26. # is in this function.  testnum starts off as the lowest
  27. # number to test, passed from num1 in the start function
  28. # and increases until it reaches the maximum number of 
  29. # maxnum, passed from num2 in the start function. 
  30.  
  31. def prime_test(testnum, maxnum):
  32.     import math
  33.     count = 3
  34.     prime = True
  35.     while testnum <= maxnum:
  36.         if testnum % 2 == 0:
  37.             testnum = testnum + 1
  38.         elif testnum % 2 != 0:
  39.             while count <= math.sqrt(testnum):
  40.                 if testnum % count == 0:
  41.                     prime = False
  42.                 else:
  43.                     count = count + 2
  44.             if prime == True:
  45.                 print testnum
  46.                 testnum = testnum +1
  47.  
  48. start()
  49.  
  50. print "Do you want to start again?"
  51. print "Type X and hit enter to exit,"
  52. endprompt = raw_input("type anything else and press enter to start again: ")
  53. if endprompt == 'x' or 'X':
  54.     print
  55.     print
  56.     print "Goodbye!"
  57. else:
  58.     start()
  59.  
Thanks for all the help so far!
Feb 28 '07 #1
7 4115
Loismustdie129
195 New Member
I worked on it for a while and I found that I didn't get an error. I did have to shift the last IF function over to the place of the ELIF function in prime_test. Or:

Expand|Select|Wrap|Line Numbers
  1. def prime_test(testnum, maxnum):
  2.     import math
  3.     count = 3
  4.     prime = True
  5.     while testnum <= maxnum:
  6.         if testnum % 2 == 0:
  7.             testnum = testnum + 1
  8.         elif testnum % 2 != 0:
  9.             while count <= math.sqrt(testnum):
  10.                 if testnum % count == 0:
  11.                     prime = False
  12.                 else:
  13.                     count = count + 2
  14.         if prime == True:
  15.               print testnum
  16.               testnum = testnum +1
  17.  
I hope this helps.
Mar 1 '07 #2
bartonc
6,596 Recognized Expert Expert
Here is the link to my original post regarding this.
Mar 2 '07 #3
Caffiend
22 New Member
Thanks Barton, i've seen that one before, and it's definitely a lot more efficient than the way I am going about it. Specifically though, I'm trying to calculate all the primes between two given numbers, mainly so that I can skip directly to the higher numbers, such as 10 ** 9. Also, for learning purposes, I can't quite figure out what is wrong with the code... Loismustdie fixed the problem with it crashing, however it now just prints out every odd number, both prime and non-prime... Does anyone know the mystery, or point me in the right direction?
Mar 2 '07 #4
bvdet
2,851 Recognized Expert Moderator Specialist
Thanks Barton, i've seen that one before, and it's definitely a lot more efficient than the way I am going about it. Specifically though, I'm trying to calculate all the primes between two given numbers, mainly so that I can skip directly to the higher numbers, such as 10 ** 9. Also, for learning purposes, I can't quite figure out what is wrong with the code... Loismustdie fixed the problem with it crashing, however it now just prints out every odd number, both prime and non-prime... Does anyone know the mystery, or point me in the right direction?
Here's a couple of functions for prime numbers - small and large:
Expand|Select|Wrap|Line Numbers
  1. def primes(low, high):
  2.     lstA = range(2, high)
  3.     lstB = []
  4.     while len(lstA) > 0:
  5.         n = lstA[0]
  6.         if n >= low:
  7.             lstB.append(n)
  8.         cnt = 1
  9.         while n*cnt < high:
  10.             n1 = n*cnt
  11.             if n1 in lstA:
  12.                 lstA.remove(n1)
  13.             cnt += 1
  14.     return lstB
  15.  
  16. # print ', '.join(map(str, primes(2, 200)))
  17.  
  18. import math
  19. def large_primes(low, high):
  20.     if high <= low:
  21.         raise ValueError, 'Argument #2 must be greater than argument #1'
  22.     elif (high-low) > 1000:
  23.         raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
  24.     pList = primes(2,200)
  25.     numList = range(low, high)
  26.     lpList = range(low, high)
  27.     for num in numList:
  28.         for p in pList:
  29.             if num % p == 0:
  30.                 lpList.remove(num)
  31.                 break
  32.     numList = lpList
  33.     for num in numList:
  34.         for i in [-1, 0, 1, 2, 3, 4]:
  35.             k = 1
  36.             while (6*k+i) < math.sqrt(num):
  37.                 if num % (6*k+i) == 0:
  38.                     try:                   # There is a bug here, therefore the try
  39.                         lpList.remove(num)
  40.                         break
  41.                     except:
  42.                         pass
  43.                 k += 1
  44.     return lpList
  45.  
  46. print ', '.join(map(str, large_primes(200000000000, 200000000100)))
  47. '''
  48. >>> 200000000023, 200000000033, 200000000041, 200000000051, 200000000069, 200000000077, 200000000093
  49. '''
  50.  
The function large_primes() ignores prime numbers less than 200 and limits the range to 1000. It works reasonably fast for 11 digits and fewer, depending on the range. I was getting this error at the noted try statement:

File "C:\SDS2_7.0\macro\Work In Progress\prime_number.py", line 130, in large_primes
if num % (6*k+i) == 0:
ValueError: list.remove(x): x not in list


If someone can figure out why I would appreciate it.
HTH, BV :)
Mar 3 '07 #5
ghostdog74
511 Recognized Expert Contributor
Here's a couple of functions for prime numbers - small and large:
Expand|Select|Wrap|Line Numbers
  1. def primes(low, high):
  2.     lstA = range(2, high)
  3.     lstB = []
  4.     while len(lstA) > 0:
  5.         n = lstA[0]
  6.         if n >= low:
  7.             lstB.append(n)
  8.         cnt = 1
  9.         while n*cnt < high:
  10.             n1 = n*cnt
  11.             if n1 in lstA:
  12.                 lstA.remove(n1)
  13.             cnt += 1
  14.     return lstB
  15.  
  16. # print ', '.join(map(str, primes(2, 200)))
  17.  
  18. import math
  19. def large_primes(low, high):
  20.     if high <= low:
  21.         raise ValueError, 'Argument #2 must be greater than argument #1'
  22.     elif (high-low) > 1000:
  23.         raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
  24.     pList = primes(2,200)
  25.     numList = range(low, high)
  26.     lpList = range(low, high)
  27.     for num in numList:
  28.         for p in pList:
  29.             if num % p == 0:
  30.                 lpList.remove(num)
  31.                 break
  32.     numList = lpList
  33.     for num in numList:
  34.         for i in [-1, 0, 1, 2, 3, 4]:
  35.             k = 1
  36.             while (6*k+i) < math.sqrt(num):
  37.                 if num % (6*k+i) == 0:
  38.                     try:                   # There is a bug here, therefore the try
  39.                         lpList.remove(num)
  40.                         break
  41.                     except:
  42.                         pass
  43.                 k += 1
  44.     return lpList
  45.  
  46. print ', '.join(map(str, large_primes(200000000000, 200000000100)))
  47. '''
  48. >>> 200000000023, 200000000033, 200000000041, 200000000051, 200000000069, 200000000077, 200000000093
  49. '''
  50.  
The function large_primes() ignores prime numbers less than 200 and limits the range to 1000. It works reasonably fast for 11 digits and fewer, depending on the range. I was getting this error at the noted try statement:

File "C:\SDS2_7.0\macro\Work In Progress\prime_number.py", line 130, in large_primes
if num % (6*k+i) == 0:
ValueError: list.remove(x): x not in list


If someone can figure out why I would appreciate it.
HTH, BV :)
did not rreally run your entire script, but you can try
Expand|Select|Wrap|Line Numbers
  1. ...
  2. numList = lpList[:]
  3. ...
  4.  
Mar 3 '07 #6
bvdet
2,851 Recognized Expert Moderator Specialist
did not rreally run your entire script, but you can try
Expand|Select|Wrap|Line Numbers
  1. ...
  2. numList = lpList[:]
  3. ...
  4.  
Thanks, but it did not help. It bombs on this number: 2000000159
Mar 3 '07 #7
bvdet
2,851 Recognized Expert Moderator Specialist
The code for large_primes() that I posted earlier was incorrect. The following seems to work correctly:
Expand|Select|Wrap|Line Numbers
  1. def large_primes(low, high):
  2.     if high <= low:
  3.         raise ValueError, 'Argument #2 must be greater than argument #1'
  4.     elif (high-low) > 30000:
  5.         raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
  6.     pList = primes(2,200)
  7.     numList = range(low, high)
  8.     lpList = range(low, high)
  9.     for num in numList:
  10.         for p in pList:
  11.             if num % p == 0:
  12.                 lpList.remove(num)
  13.                 break
  14.     numList = lpList[:]
  15.     for num in numList:
  16.         for i in xrange(9, int(math.ceil(math.sqrt(high))), 2):
  17.             if num % i == 0:
  18.                 lpList.remove(num)
  19.                 break
  20.     return lpList
  21.  
  22. pList = large_primes(20000000000, 20000001000)
  23.  
  24. >>> 20000000089, 20000000113, 20000000117, 20000000179, 20000000201, ..........
Mar 4 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

36
8350
by: Dag | last post by:
Is there a python module that includes functions for working with prime numbers? I mainly need A function that returns the Nth prime number and that returns how many prime numbers are less than N,...
11
5921
by: lostinpython | last post by:
I'm having trouble writing a program that figures out a prime number. Does anyone have an idea on how to write it? All I know is that n > 2 is prim if no number between 2 and sqrt of n...
11
7127
by: don | last post by:
Ok, this is a homework assignment, but can you help me out anyway...... I need a routine for figuring out if a number inputted by the user is a prime number or not...... all I'm asking for is Not...
4
5206
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime...
10
4407
by: Joel Mayes | last post by:
Hi All; I'm teaching myself C, and have written a prime number generator. It is a pretty inefficient implementation of the Sieve of Eratosthenes to calculate primes up to 1,000,000. If anyone...
2
2577
by: QHorizon | last post by:
Hello, I'm new to Python (I've learned everything up to iterators so far) and fairly new to Programming. This would be my first real program: #Coordinate Geometry (The whole program is not...
5
2531
by: silversnake | last post by:
I'm trying to write a program that take a input number and prints if is a prime numbers but is not working for instance, it says that 4 is prime while 5 is not. can anyone see what the problem is ....
4
2300
by: cnixuser | last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting...
0
7072
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7271
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6979
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
4998
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3160
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1498
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.