7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rustで「エラトステネスの篩」で「2.6秒で百万個」の素数を計算できる「無限シーケンス」を作ってみた

Last updated at Posted at 2017-02-12

詳しくはリンク先参照。とりあえずRustで書いてみた。


use std::collections::HashMap;

fn main() {
    let mut dict = HashMap::new();
    let mut iter = (1..).filter_map(|j| {
        let i = 2 * j + 1;
        let (factor, is_prime) = match dict.remove(&i) {
            Some(f) => (f, false),
            None => (i * 2, true),
        };
        let key = (1..)
            .filter_map(|j| {
                let k = i + j * factor;
                if dict.contains_key(&k) { None } else { Some(k) }
            })
            .next()
            .unwrap();
        dict.insert(key, factor);
        if is_prime { Some(i) } else { None }
    });
    println!("{}", iter.nth(1000_000 - 2).unwrap());
}

step_byが欲しかった。

7
5
2

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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?