0

I recently wrote a simple Python program to find prime numbers. The code is as follows:

import math

searchLimit = 20
n = 3


def findPrimes(primes):
    global n
    global searchLimit

    if n == searchLimit:
        print(primes)
        return primes

    temp = [c for c in primes if c <= round(math.sqrt(n), 0)]

    isPrime = True

    for i in temp:
        if n % i == 0:
            isPrime = False

    if isPrime:
        primes.append(n)

    n += 1
    findPrimes(primes)


foundPrimes = findPrimes([2])
print(foundPrimes)

(don't bother berating me with my use of global variables - I know it's bad practice, for this simple test I cannot imagine it making a difference)

When findPrimes is called, the program first makes sure that the search limit - in this case 20 - has not been exceeded. Afterwards, it does some arithmetic to check if the number has any prime factors. If the number is prime, it appends n to the array of primes, and then adds 1 to n and recurses. Ultimately the nature of this piece of the method should be irrelevant, as we will come to see.

When I run the program, the output is as follows:

[2, 3, 5, 7, 11, 13, 17, 19]
None

The output "[2, 3, 5, 7, 11, 13, 17, 19]" comes from print(primes) inside of findPrimes, which of course implies that primes = [2, 3, 5, 7, 11, 13, 17, 19]. However, when I return primes and set the output of findPrimes equal to foundPrimes, and print that, Python gives the output None - implying that foundPrimes, and hence the output of findPrimes, and therefore primes is null.

So, my question is: what is the source of these conflicting implications, and how do I resolve this issue to get a non-null output from findPrimes? Thanks in advance.

  • 3
    add this to your code `return findPrimes(primes)`. – Ch3steR Mar 10 '20 at 19:00
  • Output primes very many times, then a recursion depth exceeded error. Exactly what I would've expected for calling a recursive method twice in itself like that. – Convergant Mar 10 '20 at 19:02
  • 1
    Maybe we should clarify that you shouldn't be adding that line as such, but replacing the last line of your function `findPrimes(primes)` with `return findPrimes(primes)` – mypetlion Mar 10 '20 at 19:03
  • right now you're returning a result only when you enter the if. Not in any of the other recursive call! – B. Go Mar 10 '20 at 19:05
  • B. Go - the program only prints when the if statement is entered so we know that it's returning. Mypetlion - thank you, an actually working solution, rather than people who have ambiguous answers/clearly don't understand a simple 30-line program. – Convergant Mar 10 '20 at 19:10
  • 1
    @Convergant I wouldn't call the solution suggested by Ch3steR ambiguous... As an aside, variable and function names should follow the `lower_case_with_underscores` style. – AMC Mar 10 '20 at 19:27
  • Try adding a `return primes` at the end of your function. – WangGang Mar 10 '20 at 20:34

0 Answers0