We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,318 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

testing prime numbers

Hello! could i ask where there's any error in my code for testing prime numbers?
cos i tried testing 21 and 49, and they were tested as prime.
thanks!

import math
y = int(raw_input("Please input a number: "))

if  y < 2:
    print "It is not a prime number."
elif y == 2:
    print "It is a prime number."
else:
    for i in range (2,int (y+1)):
        if y%i == 0:
            print "It is not a prime number."
            break
        else:
            print "It is a prime number."
3
Contributors
2
Replies
2 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
pam1003
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

cos i tried testing 21 and 49, and they were tested as prime.
thanks!

What does this mean as "It is" or "It is not a prime number" will print y-1 times for each number tested, or until "not prime" is found. Add a print statement under the for() loop to print "i" and test with an odd number like 25, so prime is not found until 5 is tested. You only have to test for "can be divided by 2" once, and then use the step parameter of the for() to increment from 3, step 2=every other number so you don't waste time dividing by even numbers since you have already checked if it is divisible by 2. Also, the general assumption is that if you are too lazy to key in actual words instead of teeny-bopper slang, you are just lazy and looking for someone to do it for you, so there are very few responses.

woooee
Posting Maven
2,715 posts since Dec 2006
Reputation Points: 827
Solved Threads: 780
Skill Endorsements: 9

Yes, as 21=3*7, we can say for sure that your program has problem QED.

pyTony
pyMod
Moderator
6,330 posts since Apr 2010
Reputation Points: 879
Solved Threads: 989
Skill Endorsements: 27

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.0582 seconds using 2.67MB