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: -
print
-
print
-
print "This program identifies all the prime numbers"
-
print "between two given numbers"
-
print
-
-
# I just wanted the start function to take two integers
-
# and pass them to prime_test, with num1 as testnum and
-
# num2 as maxnum.
-
def start():
-
num1 = input("Please enter the lower number: ")
-
num2 = input("Please enter the higher number: ")
-
if num1 > num2:
-
print "Please input the lower number first."
-
start()
-
elif num1 == num2:
-
print "Please use 2 different numbers."
-
start()
-
elif (num1 < 0) or (num2 < 0):
-
print "Please use positive integers only please."
-
start()
-
prime_test(num1, num2)
-
-
-
# I'm not sure where the problem is, but I think it
-
# is in this function. testnum starts off as the lowest
-
# number to test, passed from num1 in the start function
-
# and increases until it reaches the maximum number of
-
# maxnum, passed from num2 in the start function.
-
-
def prime_test(testnum, maxnum):
-
import math
-
count = 3
-
prime = True
-
while testnum <= maxnum:
-
if testnum % 2 == 0:
-
testnum = testnum + 1
-
elif testnum % 2 != 0:
-
while count <= math.sqrt(testnum):
-
if testnum % count == 0:
-
prime = False
-
else:
-
count = count + 2
-
if prime == True:
-
print testnum
-
testnum = testnum +1
-
-
start()
-
-
print "Do you want to start again?"
-
print "Type X and hit enter to exit,"
-
endprompt = raw_input("type anything else and press enter to start again: ")
-
if endprompt == 'x' or 'X':
-
print
-
print
-
print "Goodbye!"
-
else:
-
start()
-
Thanks for all the help so far!
7 4135
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: - def prime_test(testnum, maxnum):
-
import math
-
count = 3
-
prime = True
-
while testnum <= maxnum:
-
if testnum % 2 == 0:
-
testnum = testnum + 1
-
elif testnum % 2 != 0:
-
while count <= math.sqrt(testnum):
-
if testnum % count == 0:
-
prime = False
-
else:
-
count = count + 2
-
if prime == True:
-
print testnum
-
testnum = testnum +1
-
I hope this helps.
bartonc 6,596
Recognized Expert Expert Here is the link to my original post regarding this.
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?
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: - def primes(low, high):
-
lstA = range(2, high)
-
lstB = []
-
while len(lstA) > 0:
-
n = lstA[0]
-
if n >= low:
-
lstB.append(n)
-
cnt = 1
-
while n*cnt < high:
-
n1 = n*cnt
-
if n1 in lstA:
-
lstA.remove(n1)
-
cnt += 1
-
return lstB
-
-
# print ', '.join(map(str, primes(2, 200)))
-
-
import math
-
def large_primes(low, high):
-
if high <= low:
-
raise ValueError, 'Argument #2 must be greater than argument #1'
-
elif (high-low) > 1000:
-
raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
-
pList = primes(2,200)
-
numList = range(low, high)
-
lpList = range(low, high)
-
for num in numList:
-
for p in pList:
-
if num % p == 0:
-
lpList.remove(num)
-
break
-
numList = lpList
-
for num in numList:
-
for i in [-1, 0, 1, 2, 3, 4]:
-
k = 1
-
while (6*k+i) < math.sqrt(num):
-
if num % (6*k+i) == 0:
-
try: # There is a bug here, therefore the try
-
lpList.remove(num)
-
break
-
except:
-
pass
-
k += 1
-
return lpList
-
-
print ', '.join(map(str, large_primes(200000000000, 200000000100)))
-
'''
-
>>> 200000000023, 200000000033, 200000000041, 200000000051, 200000000069, 200000000077, 200000000093
-
'''
-
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 :)
Here's a couple of functions for prime numbers - small and large: - def primes(low, high):
-
lstA = range(2, high)
-
lstB = []
-
while len(lstA) > 0:
-
n = lstA[0]
-
if n >= low:
-
lstB.append(n)
-
cnt = 1
-
while n*cnt < high:
-
n1 = n*cnt
-
if n1 in lstA:
-
lstA.remove(n1)
-
cnt += 1
-
return lstB
-
-
# print ', '.join(map(str, primes(2, 200)))
-
-
import math
-
def large_primes(low, high):
-
if high <= low:
-
raise ValueError, 'Argument #2 must be greater than argument #1'
-
elif (high-low) > 1000:
-
raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
-
pList = primes(2,200)
-
numList = range(low, high)
-
lpList = range(low, high)
-
for num in numList:
-
for p in pList:
-
if num % p == 0:
-
lpList.remove(num)
-
break
-
numList = lpList
-
for num in numList:
-
for i in [-1, 0, 1, 2, 3, 4]:
-
k = 1
-
while (6*k+i) < math.sqrt(num):
-
if num % (6*k+i) == 0:
-
try: # There is a bug here, therefore the try
-
lpList.remove(num)
-
break
-
except:
-
pass
-
k += 1
-
return lpList
-
-
print ', '.join(map(str, large_primes(200000000000, 200000000100)))
-
'''
-
>>> 200000000023, 200000000033, 200000000041, 200000000051, 200000000069, 200000000077, 200000000093
-
'''
-
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 -
...
-
numList = lpList[:]
-
...
-
bvdet 2,851
Recognized Expert Moderator Specialist
did not rreally run your entire script, but you can try -
...
-
numList = lpList[:]
-
...
-
Thanks, but it did not help. It bombs on this number: 2000000159
bvdet 2,851
Recognized Expert Moderator Specialist
The code for large_primes() that I posted earlier was incorrect. The following seems to work correctly: - def large_primes(low, high):
-
if high <= low:
-
raise ValueError, 'Argument #2 must be greater than argument #1'
-
elif (high-low) > 30000:
-
raise ValueError, 'The difference between argument #2 and argument #1 must be less than 1001'
-
pList = primes(2,200)
-
numList = range(low, high)
-
lpList = range(low, high)
-
for num in numList:
-
for p in pList:
-
if num % p == 0:
-
lpList.remove(num)
-
break
-
numList = lpList[:]
-
for num in numList:
-
for i in xrange(9, int(math.ceil(math.sqrt(high))), 2):
-
if num % i == 0:
-
lpList.remove(num)
-
break
-
return lpList
-
-
pList = large_primes(20000000000, 20000001000)
-
-
>>> 20000000089, 20000000113, 20000000117, 20000000179, 20000000201, ..........
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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.
|
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....
|
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...
|
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
| |
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!"
|
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;
|
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...
|
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...
|
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...
|
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,...
| |
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |