1,105,263 Community Members

testing prime numbers

Member Avatar
pam1003
Newbie Poster
1 post since Sep 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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."
Member Avatar
woooee
Posting Maven
2,793 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
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.

Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

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

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article