简体   繁体   中英

What's the issue with simple prime-finding code?

I\\ma absolutely beginner. Just trying to tweak down some basics. But somehow i cant get this running. This is maybe some stupid oversight or I don't know. Can anyone take a look at this?

import math

def prime(n):
    if n == 1:
        return False
    maxx_d = math.floor(math.sqrt(n))
    for d in range(2 , 1+ maxx_d):
        if n % d == 0:
            return False

        return True
for n in range(1, 21):
    print(n, prime(n))

It's supposed to be show prime numbers but instead this is what get printed:

1 False
2 None
3 None
4 False
5 True
6 False
7 True
8 False
9 True
10 False
11 True
12 False
13 True
14 False
15 True
16 False
17 True
18 False
19 True
20 False

Per orhtej2's comment , "Indentation on return True is too deep." This will work:

def prime(n):
    if n == 1:
        return False
    maxx_d = math.floor(math.sqrt(n))
    for d in range(2, 1+maxx_d):
        if n % d == 0:
            return False
    return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM