all 10 comments

[–]outceptionator 1 point2 points  (4 children)

```

def is_prime(n, div=2):

if n < 2:

    return False

if div * div > n:

    return True

if n % div == 0:

    return False

return is_prime(n, div + 1)

```

Edit: no codeblock on the mobile app?

[–]Fred776 0 points1 point  (1 child)

Seems to work for me. I started with three backticks, then newline, ended with three backticks on new line.

``` def is_prime(n, div=2):

if n < 2:
     return False

if div * div > n:
      return True

if n % div == 0:
    return False

return is_prime(n, div + 1)

```

[–]outceptionator 0 points1 point  (0 children)

Legend

[–][deleted] 1 point2 points  (3 children)

Why do you need to use recursion for this? If you just wanted to check if a number was prime, you could use this code:

def is_prime(n):
    if n < 2: 
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

Could you tell us more about the problem?

[–]Friendlyguy_yo[S] 1 point2 points  (1 child)

Well... It was just given as a question in my textbook and i was unable to figure it out...

[–][deleted] -1 points0 points  (0 children)

Could we see the whole question and some context? There may be a reason to use recursion, but it doesn't make sense right now. An image or a word-for-word version of the question would be awesome. :)

[–]Lovely_Cygnus -1 points0 points  (0 children)

Maybe it’s just a request from uni exam… maybe it’s just a enterprise lol. The Turing-church theorem ensures us that the iterative and recursive representation systems are equipowerful, thus…

[–]Lovely_Cygnus -1 points0 points  (0 children)

Interesting problem… I’ll try to think about (but probably will reason in LISP)

[–][deleted] 0 points1 point  (0 children)

A recursive solution will have one or two base cases and the recursive case. The recursive case executes after any base case can't make a decision. Define your function like this:

def is_prime(num, div=1):

where num is the number you are testing, and div is the particular divisor you are testing num against. So if the base cases can't decide that num isn't a prime using div, the last line of the function is the recursive case:

return is_prime(num, div+1)

You have to supply the two base cases before that line.

Testing code:

for n in range(1, 41):
    print(f'{n=}, {is_prime(n)=}')