Function to determine whether or not an int is prime
Im stuck with the following:
Define a function isPrime(number) that takes in a number as argument and return True if the number is a prime number.
Hint: A number, x is a prime number if it is only divisible by 1 and x itself.
By definition, 1 is not a prime number.
Examples
>>> isPrime(97)
True
>>> isPrime(1)
False
>>> isPrime(-2)
False
# Hint: Step through the range between (2, number-1),
# and determine if the number is divisible using the modulus operator.
def isPrime(x):
how should i go about this? i dont understand it. Any help is appreciated.
p.s the topic this exercise is a part of is 'Conditionals'
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
# and determine if the number is divisible using the modulus operator.
modulus returns the remainder of a number
ex.
>>> 10%4
2
>>> 10%2
0
if the answer is 0 then the number is perfectly divisible
this should give you a hint if the number is prime
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
sorry ihatehippies, your code doesn't work.
And thanks zeroliken, though i still dont get it, haha
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
my bad
def isprime(num):
if num < 2: return False
elif num == 2: return True
for x in xrange(2,num-1):
if not num % x: return False
return True
as mentioned above '%' returns the remainder
6%3 = 2 remainder 0, so it returns 0
6%4 = 2 remainder 2, so it returns 2
the function goes through the numbers between 2 and the number-1 and checks to see if any number is perfectly divisible.
Thanks , very helpful!
pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0