1.11M Members

testing prime numbers

 
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."
 
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.

 
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 six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article