473,840 Members | 1,662 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 4140
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\ma cro\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\ma cro\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
8417
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, but a prime number tester would also be nice. I'm dealing with numbers in the 10^6-10^8 range so it would have to fairly efficient Dag
11
5949
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 (inclusivly) evenly divides n.
11
7166
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 the exact code ( well maybe a little) but the logic or algorithm to tell whether or not a number is prime....
4
5229
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 and 0 if it isn't. I have spent ages just getting this code to work and i'm worried i need to rip it to bit to get this function to work ! The function is: int prime(int number) here is my code so far: #include...
10
4446
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 has time to critic and offer my some feedback I'd be grateful Thanks Joel
2
2613
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 shown) import math import sys print "Welcome to the Coordinate Geometry Calculator!"
5
2539
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 . thanks in advance #include <stdio.h> #include <math.h> #define TRUE 1; #define FALSE 0;
4
2328
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 any prime numbers and seems to be only to be printing one value of zero from the array that I am trying to store the prime numbers detected in. I believe the zero is coming from the value already stored in the array when I initialzed it, which means...
0
9860
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9699
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10922
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10660
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10301
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7023
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4498
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 we have to send another system
2
4076
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.