1. 程式人生 > >[Python程式設計]判斷和輸出素數的多種方法

[Python程式設計]判斷和輸出素數的多種方法

1.for迴圈輸出100以內的素數

def get_prime_scope(scope=100):
    numlist = []
    i = 2
    for i in range(2, scope + 1):
        j = 2
        for j in range(2, int(math.sqrt(i))):
            if (i % j == 0):
                break
        else:
            numlist.append(i)
    print(numlist)

2.while迴圈輸出前20個素數

# 輸出前20個素數
def is_prime(number):
    for i in range(2, int(math.sqrt(number))):
        if (number % i) == 0:
            return False
    return True


def get_prime(count=20):
    numlist = []
    i = 2
    while True:
        if is_prime(i):
            numlist.append(i)
            count -= 1
        if
0 == count: break i += 1 print(numlist)

列表推導輸出50以內的素數

def is_prime(number):
    for i in range(2, int(math.sqrt(number))):
        if (number % i) == 0:
            return False
    return True
    
def get_prime_compre(scope=50):
    print([n for n in range(2, scope + 1) if
is_prime(n)])

4.filter+lambda輸出30以內的素數

def get_prime_filter(scope=30):
    ft = filter(lambda x: not [x % i for i in range(2, int(math.sqrt(x)) + 1) if x % i == 0], range(2, scope + 1))
    print(list(ft))

測試

get_prime()  #前20個
get_prime_scope() #100以內
get_prime_compre() #50以內
get_prime_filter() #30以內
#輸出
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]