Reputation: 1
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?
Upvotes: 0
Views: 72
Reputation: 45750
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))
Upvotes: 1