Taint
Taint

Reputation: 67

Why is my modulo condition in my prime number tester not working?

I'm trying (and failing) to write a simple function that checks whether a number is prime. The problem I'm having is that when I get to an if statement, it seems to be doing the same thing regardless of the input. This is the code I have:

def is_prime(x):
    if x >= 2:
        for i in range(2,x):
            if x % i != 0:    #if x / i remainder is anything other than 0
                print "1"
                break
            else:
                print "ok"
        else:
            print "2"
    else: print "3"

is_prime(13)

The line with the comment is where I'm sure the problem is. It prints "1" regardless of what integer I use as a parameter. I'm sorry for what is probably a stupid question, I'm not an experienced programmer at all.

Upvotes: 1

Views: 288

Answers (4)

D Bro
D Bro

Reputation: 563

Try using return statements instead of (or in addition to) print statements, eg:

from math import sqrt # for a smaller range

def is_prime(x):
    if x <= 2:
        return True
    for i in range(2, int(sqrt(x)) + 1):
        if x % i == 0:
            print "%d is divisible by %d" % (x,i)
            return False
    return True    

is_prime(13)
True

is_prime(14)
14 is divisible by 2
False

Upvotes: 0

Elazar
Elazar

Reputation: 21615

This kind of checks can be single expression:

def is_prime(n):
    return n>1 and all(n%k for k in range(2,n//2))

Upvotes: 0

Jared
Jared

Reputation: 26397

Your code is actually really close to being functional. You just have a logical error in your conditional.

There are some optimizations you can make for a primality test like only checking up until the square root of the given number.

def is_prime(x):
    if x >= 2:
        for i in range(2,x):
            if x % i == 0: # <----- You need to be checking if it IS evenly
                print "not prime" # divisible and break if so since it means
                break             # the number cannot be prime
            else:
                print "ok"
        else:
            print "prime"
    else:
        print "not prime"

Upvotes: 3

tacaswell
tacaswell

Reputation: 87396

The problem is this line:

if x % i != 0: 

You are testing if x % i is not 0, which is true for any pair of integers that are relatively prime (hence, you always get it printed out)

It should be:

if x % i == 0:

Upvotes: 2

Related Questions