473,854 Members | 1,769 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 2613
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
8419
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
7284
by: Peter Olcott | last post by:
www.halting-problem.com
4
2810
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
2447
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
2124
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
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
6
5298
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
2607
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
9899
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
11024
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...
0
10672
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
10740
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
9510
agi2029
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...
1
7909
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
5738
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4550
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
3
3182
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.