0

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
user3672933
  • 17
  • 3
  • 7
  • See the links it will help. http://stackoverflow.com/questions/18833759/python-prime-number-checker http://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python – Tanmaya Meher Jul 31 '14 at 09:17
  • Has your teacher taught your recursion or looping constructs? – James Mills Jul 31 '14 at 09:18

3 Answers3

1

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.
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

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

for i in range(2,number)
    if number%i == 0:
          return false
user3766332
  • 319
  • 1
  • 5
  • 17
0
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)
Sebastian
  • 21
  • 3