0

I am trying to make a function that tells you if a number is prime or not using the any() method. This is what I have:

def prime(n):
    if any(n % i == 0 for i in range(1, n + 1)) != True:
        print("Prime")
    else:
        print("Not Prime")

prime(5)

However it is giving me:

Not Prime

every single time, even when I give a prime number.

Can someone please help me out?

1
  • 1
    As an aside from the answer already given, note that for any boolean b, if b != True would be written more idiomatically as if not b. Commented Jun 5, 2018 at 11:43

1 Answer 1

1

Everything is divisible by 1, so that check will consider everything as non-prime. You need to set the lower bound to check to 2 instead.

As pointed out in the comments by @ForceBru, the upper bound is incorrect as well. You don't want to check if n is divisible by itself, since it always will be.

Change your range in the comprehension to just:

range(2, n))
Sign up to request clarification or add additional context in comments.

4 Comments

Also, n % n == 0 as well.
Then again why not put a not in front of the any and remove the != True. It would make things clearer.
To significantly speed up the test for larger numbers you should stop checking above the square root of n.
All good points, but they kind of detract from the main problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.