user3053452
user3053452

Reputation: 675

Python - check if it's prime number

I know that this question was asked way too many times, but I'm not searching for the fastest algorithm. I'd only like to know what I'm doing wrong with my code since it's faulty.

import math

def is_prime(number):
    for i in range (2, 1+ int(math.sqrt(number))):
        if number % i == 0:
            return 0
        else:
            return 1

choice = int(input("Check if it's prime: "))
if is_prime(choice):
    print ("{} is a prime number".format(choice))
else:
    print ("{} is not a prime number".format(choice))

If I test this program for most numbers it will return correct response, but if I check any square number it will say that it's a prime. So any suggestions what I'm doing wrong?

Upvotes: 0

Views: 1357

Answers (1)

trincot
trincot

Reputation: 351403

You are returning immediately in the first iteration of the loop ... always.

Instead only return immediately when you know it is not a prime, else keep going:

def is_prime(number):
    for i in range (2, 1+ int(math.sqrt(number))):
        if number % i == 0:
            return 0
    return 1

Upvotes: 5

Related Questions