LoginSignup
6
4

More than 5 years have passed since last update.

素数ライブラリ(sieve)の使い方 (+1億以下の素数の和計算パフォーマンス)

Last updated at Posted at 2019-04-05

Python の素数用ライブラリ (scipy.sieve)  の基本的な使い方:

ライブラリ読込:

from sympy import sieve

※Google colabratory 上では sympy はデフォルトで利用可能

素数の判定:

内部的には「エラトステネスの篩」 のアルゴリズムが巧妙に用いられている。(裏で自動的に素数リストの作成、拡張等を行い、キャッシュされる)

6 in sieve
 #False

7 in sieve
 #True

素数リスト(ジェネレータ)

print([i for i in sieve.primerange(7, 18)])
#[7, 11, 13, 17]

1億までの素数の和

こちらのページ
では、1569秒かかった1億までの素数の和の計算ですが
Google Colaboratory + Pythonのライブラリでは53秒でした。

%time sum(sieve.primerange(1,100000000))
#実行結果:
CPU times: user 53.7 s, sys: 1.33 s, total: 55 s
Wall time: 55.1 s
279209790387276


6
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4