Python 3 で数学を。

Python 3 とライブラリで数学の問題を解いていきます。統計学や機械学習はときどき。

素数。(Python 3)

使用するライブラリ

なし

Python 3 コード

prime_numbers.py

#!/usr/bin/env python3


"""(docstring)
"""


def prime_numbers(num):
    """(docstring)
    """
    prime_num_list = []
    for n1 in range(2, num+1):
        for n2 in range(2, n1):
            if n1 % n2 == 0:
                break
        else:
            prime_num_list.append(n1)
    return prime_num_list


if __name__ == '__main__':
    for n in range(2, 111, 10):
        print(prime_numbers(n))
        print('')
        print('-'*79)

出力

(自分のターミナル上での改行がブログでは反映されないが)

$ python3 prime_numbers.py
[2]

-------------------------------------------------------------------------------
[2, 3, 5, 7, 11]

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

-------------------------------------------------------------------------------
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

-------------------------------------------------------------------------------
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]

-------------------------------------------------------------------------------
[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, 31, 37, 41, 43, 47, 53, 59, 61]

-------------------------------------------------------------------------------
[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]

-------------------------------------------------------------------------------
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]

-------------------------------------------------------------------------------
[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, 101]

-------------------------------------------------------------------------------