473,480 Members | 1,688 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Help, determining if an input value is prime?

15 New Member
I'm doing some reading in a python book and am doing one of the chapter exercises but I cant figure out how to get it to work and was hoping some of you python guru's could help out?

Heres description of the problem to be solved:

"A positive whole number n > 2 is prime if no number between 2 and the square root of n (inclusive) evenly divides n. Write a program that accepts a value of n as input and determines if the value is prime. If n is not prime, your program should quit as soon as it finds a value that evenly divides n."

Heres the code I have so far but it doesnt work very good...

Expand|Select|Wrap|Line Numbers
  1. def main():
  2.  
  3.     import math
  4.  
  5.     print "This program determines if a number you enter is prime or not.\n"
  6.     n = input ("Please enter a number greater than 1: ")
  7.  
  8.     n = abs(n)
  9.     i = 2
  10.     while i <= math.sqrt(n):
  11.         if n % i == 0:
  12.             print n, "is not a prime number"
  13.         i += 1
  14.     print n, "is a prime number!"
  15.  
  16. main()
  17.  
It tells me if a number is prime, but if it isnt prime it tells me it isnt, then tells me it is! LOL. I'm still a newbie when it comes to python...

I was able to get this far, but as far as "quitting as soon as it finds a value that evenly divides n." I have no clue how to do that...

Could someone please help?

Thanks a million!
Mar 14 '08 #1
6 6983
Laharl
849 Recognized Expert Contributor
First off, do your importing at the top of the file, outside of functions as a general rule. There are times later you will need to change this, but for now just put them up there.

As to your extra message, that's because your code automatically executes the print statement after the while loop. A simple way to fix this is to use a boolean, which can have True or False values. Call it, say, found and default it to False, then if a non-prime is found, set it to True and at the end, if it's still False, print that it's prime.
Mar 14 '08 #2
sigkill9
15 New Member
Okay, I tried to do what you suggested. Here is the updated code and the output, but its still doing something strange...

New code:
Expand|Select|Wrap|Line Numbers
  1. import math
  2.  
  3. def main():
  4.  
  5.     print "This program determines if a number you enter is prime or not.\n"
  6.     n = input ("Please enter a number greater than 1: ")
  7.     found = False
  8.     n = abs(n)
  9.     i = 2
  10.     while i <= math.sqrt(n):
  11.         if n % i == 0:
  12.             found = False
  13.             print n, "is not a prime number"
  14.         else:
  15.             found = True
  16.         i += 1
  17.  
  18.     if found == True:
  19.         print n, "is a prime number!"
  20.  
  21. main()
New result, prime number:
Please enter a number greater than 1: 37
37 is a prime number!


New result, not prime:
Please enter a number greater than 1: 9
9 is not a prime number


New result, large number:
Please enter a number greater than 1: 78999
78999 is not a prime number
78999 is not a prime number
78999 is not a prime number
78999 is a prime number!


What am I doing wrong?
Mar 14 '08 #3
Laharl
849 Recognized Expert Contributor
There's a couple issues here: First, don't print before the loop is done, since if more than one divisor exists, it'll print multiple times. Second, the only time you need to change found is if you find a divisor.
Mar 14 '08 #4
bgeddy
16 New Member
Also you really need to look into breaking out of the loop when a divisor is found. Maybe there is a simple statement to break out of a while loop ? When approaching a problem like this it helps to work the logic out in English (sometimes called pseudo code) first so for the loop part:

Expand|Select|Wrap|Line Numbers
  1. while divisor is less than or equal to the square root of number:
  2.         test if number mod divisor equals zero:
  3.               yes so set found to true and
  4.                 exit loop
  5.              else no so increment divisor
  6.                 continue loop
  7.  
  8. is found set to true ?
  9.     yes so print number " is not a prime"
  10.     else print numer "is a prime"
  11.  
Hopefully you can follow the logic of this (I'm not following any standards here). It should now be simple to translate this to python.

Check the problem decription, what's the smallest number you should be prompting for ?
Mar 14 '08 #5
raubana
56 New Member
well, this would need two things:
1) a divisable list
2) the "check-if-it's-prime" part

the first part would require you to fin all the factors of the number
Expand|Select|Wrap|Line Numbers
  1. def divisable(x):
  2.    y=x
  3.    #this is here so you don't edit the real value
  4.  
  5.    list=[]
  6.    #this will hold all our factors
  7.  
  8.    number = 1
  9.    #this is the number we'll divide x by
  10.    while number<y:
  11.       if float(y)/float(number)==y/number: #this makes sure it is a whole number
  12.          list.insert(y/number)
  13.    return list
  14.  
so now we have a command that finds all the factors of a number, now we find out if it's prime. Now we all know that a prime number has only two factors (1 and itself), so all you have to do is find the length of the list to find if it's prime

Expand|Select|Wrap|Line Numbers
  1. while True: #this is an infinite loop
  2.     x=input("Tell me your number: ")
  3.     if len(divisable(x))==2:
  4.        print str(x)+"is prime."
  5.     else:
  6.        print str(x)+"is NOT prime."
  7.  
  8.     print
  9.  
  10.  
... so now we can run the program and you would get something like this:

Expand|Select|Wrap|Line Numbers
  1. >>>
  2. Tell me your number: 5
  3. 5 is prime.
  4.  
  5. Tell me your number: 12
  6. 12 is NOT prime.
  7.  
BTW this is not the most effective way, but it works!
Mar 14 '08 #6
bvdet
2,851 Recognized Expert Moderator Specialist
well, this would need two things:
1) a divisable list
2) the "check-if-it's-prime" part

the first part would require you to fin all the factors of the number
Expand|Select|Wrap|Line Numbers
  1. def divisable(x):
  2.    y=x
  3.    #this is here so you don't edit the real value
  4.  
  5.    list=[]
  6.    #this will hold all our factors
  7.  
  8.    number = 1
  9.    #this is the number we'll divide x by
  10.    while number<y:
  11.       if float(y)/float(number)==y/number: #this makes sure it is a whole number
  12.          list.insert(y/number)
  13.    return list
  14.  
so now we have a command that finds all the factors of a number, now we find out if it's prime. Now we all know that a prime number has only two factors (1 and itself), so all you have to do is find the length of the list to find if it's prime
All you need is integer math. You can use the modulo operator to determine if variable x is divisible by number. Also there is no need in checking number when it exceeds the square root of x. It is not a good idea to use a variable name that is the same as a built-in Python function (list).

Following is the function I use to calculate the positive proper divisors of a given number:
Expand|Select|Wrap|Line Numbers
  1. def proper_divisors(num):
  2.     if not num%2:
  3.         start, stride = 2, 1
  4.     else:
  5.         start, stride = 3, 2
  6.     factlist = [1,]
  7.     for i in xrange(start, int(num**0.5)+1, stride):
  8.         if not num%i:
  9.             factlist.append(i)
  10.             if not i*i == num:
  11.                 factlist.append(num/i)
  12.     factlist.sort()
  13.     return factlist
Example:
Expand|Select|Wrap|Line Numbers
  1. >>> proper_divisors(39438620)
  2. [1, 2, 4, 5, 10, 13, 20, 26, 52, 65, 130, 260, 151687, 303374, 606748, 758435, 1516870, 1971931, 3033740, 3943862, 7887724, 9859655, 19719310]
  3. >>> 
If all you want to do is check if a number is prime, you can do the same as above without building a list.
Expand|Select|Wrap|Line Numbers
  1. def is_prime(n):
  2.     if n < 2:
  3.         return False
  4.     elif n == 2:
  5.         return True
  6.     elif not n%2:
  7.         return False
  8.     for i in xrange(3, int(n**0.5)+1, 2):
  9.         if not n%i:
  10.             return False
  11.     return True
Then all you need to do is check for True or False.
Expand|Select|Wrap|Line Numbers
  1. def main():
  2.     print "This program determines if a number you enter is prime or not.\n"
  3.     n = input ("Please enter a number greater than 1: ")
  4.     if is_prime(n):
  5.         print '%d is a prime number.' % n
  6.     else:
  7.         print '%d is not a prime number.' % n
  8.  
  9. main()
Mar 14 '08 #7

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

Similar topics

1
36264
by: ck388 | last post by:
I'm trying to perform a select query on an oracle database but I get this error. ORA-01840: input value not long enough for date format My query is: SELECT * FROM TIGER.VIEW_TNW_MAINSTREAM...
2
7559
by: lehmann | last post by:
Hello, Is it possible to have a disabled input in a form whose value could be sent when the form is submitted. I just need the user not to be able to change the input value, but this value is...
1
1381
by: Demoso | last post by:
Hi What's wrong with this line: document.write('<input style="width: 260px;" type="button" id="button2" onmouseover="mover(\'button2\',\'green\');" onmouseout="mover(\'button2\',color2);" ...
10
31658
by: Dwizz | last post by:
Hello, I really hope that someone can help me resolve my problem, I've been working on it for the past few days, to no avail. I have an asp:label which gets its value from the database, but what...
2
3816
by: Jeff | last post by:
I created a form page with HTTP Authentication that works with a MySQL backend. In addition to a username and password, there is a 3rd field tied to each entry. For example: username: 1111...
2
3339
by: whojustdenyme | last post by:
Hey guys, I'm new to C and programming..so I need some help. I need a way to round an INPUT number to an INPUT value so for ex: enter a decimal: 3.1459 enter the number to round: 3 Answer:...
2
2026
by: vinkumar | last post by:
Hi, I have to search for string and replace with user input value using js. I have used inner HTML (objExplorer.Document.body.innerHTML) to get user input. (Eg: If user inputs web port no. as...
2
3064
by: Chris Riesbeck | last post by:
I assume the answer to this is "no" with no workarounds, but just checking. I have a page I open locally from my filesystem for "scrubbing" Microsoft Word generated junk from HTML. In Firefox 2,...
6
3737
by: gsuns82 | last post by:
Hi all, Is it possible to read the input value given by the user by ctrl+v,how do we use java script to read the input? example: If the user selects a value using ctrl+c from some where...
2
7226
by: jerald m | last post by:
Hi, how can i pass the user input value of ( in text box field) to the another Jsp in url? Form Code <td> <input type="text" name="dil_ProjectCode" id="dil_ProjectCode"> </td>
0
7037
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,...
0
6904
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...
1
6732
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...
0
6886
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...
1
4768
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
4472
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
2990
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
2976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1294
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.