user3672933
user3672933

Reputation: 17

python check prime, stuck at one point

This was the question our teacher gave us:

"One way to determine whether or not a number is a prime number is as follows:

if the number < 2, then return False

if the number is 2, then return True

for each value of i, where i >=2 and i < number:

if i divides the number evenly, then return False

return True"

I've managed to work through most of it, but was stuck when it said 'for each value of i, where i >=2 and i < number:' how do I write this in code?

if number < 2:    
    return False
if number == 2:
    return True
?????????
    if i%2 == 0:
        return False
return True

Upvotes: 0

Views: 137

Answers (3)

Sebastian
Sebastian

Reputation: 21

def isprime(num):
 #this is the part you are missing
 for divider in range(2,num):
   if num%divider == 0:
     return False
     #end of missing part

 return not num%2 == 0 or num==2 or num==0



for i in range(0,200):
    if isprime(i): print i, isprime(i)

Upvotes: 0

user3766332
user3766332

Reputation: 329

You will need to start a loop from 2 to the number

for i in range(2,number)
    if number%i == 0:
          return false

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881663

Yo need a loop to check all numbers from 2 to one less than the number being checked. There are better ways to do it (such as only checking up to the square root of the number) but a simplistic algorithm would be:

def isPrime (n):
    if n < 2:
        return False
    for x in range (2, n):
        if n % x == 0:
            return False
    return True

So, in terms of what you need to add to your code:

  • a loop iterating some variable from two up to one less than the number.
  • checking modulo with that variable rather than the hard-coded 2.

Upvotes: 1

Related Questions