0

so I've written a function which checks if a number is a prime

def prime_checker(prime):
    limit = int(math.sqrt(prime))
    x = 2
    while x <= limit:
        if prime % x != 0:
            x += 1
            if x == limit:
                print("%d is prime" % prime)
                return True
        else:
            print("%d Not a prime" % prime)
            return False

prime_checker(199)

Now I want to create a function which tests numbers with prime_checker method and append this number to a list if it is prime. My attempt for it is:

def prime_counting():
    list_of_primes = []
    for x in range(10):
        if prime_checker(x) == True:
            list_of_primes.append(x)
    print(list_of_primes)

prime_counting()

However, this doesn't work. Is there any way to fix this?

Sabih
  • 325
  • 1
  • 3
  • 12
  • 2
    `prime_checker(9)`, `prime_checker(25)`, `prime_checker(49)`, `prime_checker(121)` – what do these suggest about `limit`? – Ry- Nov 22 '16 at 17:21
  • 4
    `prime_checker(3)` returns `None`. That seems like a good place to start debugging. – Kevin Nov 22 '16 at 17:22
  • 1
    "However, this doesn't work. Is there any way to fix this?" -- There's almost certainly a way to fix it. The question is what is broken? Is there an exception? Is the output wrong? Are you sure that your `prime_checker` function is working correctly? etc. – mgilson Nov 22 '16 at 17:23
  • 1
    your `prime_checker` can potentially have no return, I believe that is the current problem you are facing – depperm Nov 22 '16 at 17:24
  • You might want to look at http://stackoverflow.com/questions/15285534/isprime-function-for-python-language to see why your prime checker is not correct? – Fallenreaper Nov 22 '16 at 17:26
  • Thanks all, I've fixed prime_checker and now it works. – Sabih Nov 22 '16 at 17:35

2 Answers2

0

Your prime checker does not work in some cases. Try

def prime_checker(prime):
    limit = int(math.sqrt(prime))
    for x in range(2, limit + 1):
        if prime % x == 0:
            return False
    return True
blue_note
  • 27,712
  • 9
  • 72
  • 90
0

You have almost done it correctly, there is only a minute (logical) error in the order of one of the statement.

def prime_checker(prime):
limit = int(math.sqrt(prime))
x = 2
while x <= limit:
    if prime % x != 0:
        if x == limit:
            print("%d is prime" % prime)
            return True
    x += 1
    else:
        print("%d Not a prime" % prime)
        return False

This is the updated prime_checker function. I have only found out your error. Otherwise your logic was absolutely correct. :)

Vaibhav Singh
  • 932
  • 7
  • 20