0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Rust]エラトステネスの篩を使って素数を生成

Last updated at Posted at 2024-10-20

エラトステネスのふるいを使って素数を発生するプログラムです。

Rustで書いてみました。

RustはPythonと違って、型にうるさいですね。こうでもしないとバグが取れないのかもしれませんが。

コンパイル:rustc sieve.rs
実行:./sieve N

sieve.rs
use std::env;
fn main() {
    let args: Vec<String> = env::args().collect();
    let n=&args[1];
    let n:i32=n.parse().unwrap();
    let f:Vec <i32>=sieve(n);
    let l:i32=f.len() as i32;
    println! ("{:?} : {:?} ",l,f);
}

fn sieve(n:i32)->Vec<i32> {
  let mut tab:Vec<i32>=(2..=n).rev().collect();
  let mut l:Vec<i32>=vec![];
  while !tab.is_empty() {
    let v:i32=match tab.pop() { Some(value)=>value, None=>1 };
    l.push(v);
    tab.retain(|&x| x%v !=0);
    }
  l
}
0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?