473,606 Members | 2,110 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with returning prime number in a simple calculation program

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!"
print "Type 'terms' for a list of commands"

def main():
print
command = raw_input("Comm and? ")
if command == "terms":
terms()
main()
elif command == "distance":
distance()
main()
elif command == "slope":
slope()
main()
elif command == "endpoint":
endpoint()
main()
elif command == "midpoint":
midpoint()
main()
elif command == "prime":
prime()
main()
elif command == "quit":
sys.exit
else:
print "Not a valid command"
main()

#...Declaring functions here...

def prime():
num = input("Number ")
i = num - 1
divcounter = 0
while i 1:
if num % i != 0:
divcounter += 1
i -= 1
if divcounter == num - 2:
print num, "is a prime number"
else:
print num, "is not a prime number"

#Start the program
main()

As it says in the title, I'm having trouble with the prime number
function. It will print the sentence if the number is prime, but it
if isn't, the program goes into a state in the terminal where the
program never ends and you can just keep on typing. Maybe the else
statement is ineffective? Any ideas on how to fix this?

Mar 3 '07 #1
2 2596
QH******@gmail. com wrote:
[reformatted indentation]
def prime():
num = input("Number ")
i = num - 1
divcounter = 0
while i 1:
if num % i != 0
divcounter += 1
i -= 1
if divcounter == num - 2:
print num, "is a prime number"
else:
print num, "is not a prime number"
[...]
As it says in the title, I'm having trouble with the prime number
function. It will print the sentence if the number is prime, but
it if isn't, the program goes into a state in the terminal where
the program never ends and you can just keep on typing.
Sure thing. You designed the function to behave this way.

Look at the while loop -- especially think what happens if
(num % i == 0). i will never be decremented then and the function
will not terminate.

Try inserting print statements for debugging if you don't get what I
meant here.
Maybe the else statement is ineffective?
No one can read your thoughts. In which way effective?

Regards,
Björn

--
BOFH excuse #86:

Runt packets

Mar 3 '07 #2
On Sat, 03 Mar 2007 15:36:36 -0800, QHorizon wrote:
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!"
print "Type 'terms' for a list of commands"

def main():
[snip big boring series of if...elif... statements]

You're eventually going to run into a run time recursion error if you run
that for long enough. Can you see why?

A better way to do a command loop is something like this:
def bad_command():
# called when the user enters an unrecognized command
print "Unknown command, please try again"

class QuitException(E xception):
# used for exiting the loop
pass
def main():
# Make a "dispatch table" that maps the name of a command
# (as typed by the user) with a function to call.
dispatcher = {'slope': do_slope,
'primes': do_primes,
'quit': do_quit,
# ... and more here
}
try:
# loop forever (until we jump out of it)
while True:
cmd = get_command_fro m_user()
# you have to write get_command_fro m_user yourself
func = dispatcher.get( cmd, bad_command)
result = func()
print result
except QuitException:
print "Goodbye, come again soon!"
Now you just need to define your individual functions do_slope, do_primes,
etc. The only "special" one is do_quit.

def do_quit():
raise QuitException
Now let's look at the do_primes function. (You call it "prime".)
def prime():
num = input("Number ")
That's a good way to have malicious users do really, really really bad
things to your PC.

Safer is to do this:

num = int(raw_input(" Number "))
i = num - 1
divcounter = 0
while i 1:
if num % i != 0:
divcounter += 1
i -= 1
That's an inefficient algorithm, if it even works. I'm not sure that it
works, and I'm too lazy to find out :)

if divcounter == num - 2:
print num, "is a prime number"
else:
print num, "is not a prime number"
This will only work if divcounter happens to equal the original number
less two. If it equals something else, nothing will be printed.

Here's a simple algorithm to check if a number is prime.

# Warning: untested.
def do_primes():
num = int(raw_input(" Number ")
if num <= 1:
return "%n is not prime" % num
if num == 2:
return "%n is prime" % num
elif num % 2 == 0:
# even numbers other than 2 aren't prime
return "%n is not prime" % num
for i in range(3, num, 2):
if num % i == 0:
return "%n is not prime" % num
return "%n is prime" % num
Now, this is deliberately not an efficient algorithm. There are things you
can do to make it more efficient, or you can re-write it completely.
The thing to remember is, don't PRINT the result, RETURN it. Your
do_primes() function should only calculate the result, and pass that
result up to the main loop for printing (or writing to a text file, or
emailing, or whatever).

Have fun!

--
Steven.

Mar 4 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

36
8376
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
117
7156
by: Peter Olcott | last post by:
www.halting-problem.com
4
2800
by: Trevor Best | last post by:
I have a report that's fairly simple, page headers and footers, detail has a subreport in (can vary in length). The customer wanted a signature block for them, their client and 3rd party. This was no problem, couple of boxes and labels in the report footer. Now customer wants this signature block on the foot of page 1 (stoopid IMO as that implies people read page 1 where at the end implies they read past page 1 at least). Anyway to...
10
2421
by: randomtalk | last post by:
hello, i have another problem i feel that i have to be missing something.. Basically, i've written a recursive function to find all the prime up to a number (lim).. here is the function: The function basically takes in a list of all the prime number found, it takes the next number to be tested for (next) and the limit it will go up to. It divide next by the list of previous prime numbers if next is not bigger than lim, count up all the...
18
2100
by: baltimoredude1 | last post by:
Hi I was writing a simple code to generate the first 100 prime numbers. Everything looks fine to me except the output of the program. What's wrong with it? I am attaching the program as well as the output. Would appreciate if someone could mail me at baltimoredude1@gmail.com Thanks A M Rahman
10
4419
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
6
5288
by: UofFprogrammer | last post by:
For a fun challenge, I am trying to create a C++ program that will determine if a number is prime. I am getting to problems when I reach a large values (over 9 or so digits). How can I increase the number of digits i can use? For example, when i use the number 4362206209 (which I know for a fact is prime) it returns 2 as a factor, which it isn't. Eventually, I would like to get to long (50+ digit) numbers. I know this calculation would take...
33
2570
by: r034802n | last post by:
A Judagrali series: Find the 4th prime number N such that N=NumberOfDigits(Q) where N is prime AND Q is prime AND where Q=2p-1 where P is prime. Example the 1st prime number N is 2, because 2=NumberOfDigits(31) because 2 is prime and because 31=2^5-1 and because 5 is prime. We are looking for the 2nd,3rd, 4th prime number N in the Judagrali series as well as its corresponding Q and P values. Hints: 1 The 4th N corresponds to a very large...
0
7939
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
8428
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8078
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
8299
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...
1
5962
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 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...
0
5456
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
3964
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1548
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1285
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.