0

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'

3
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by pwolf
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

Edited by zeroliken: n/a

-1
def isprime(num):
    for x in range(2, num):
        if num % x == 0: return False
    return True
Votes + Comments
please let OP to do his part
0

sorry ihatehippies, your code doesn't work.

And thanks zeroliken, though i still dont get it, haha

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.

Edited by ihatehippies: n/a

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!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.