エラトステネスの篩を使って1000以下の素数を列挙する方法

エラトステネスの篩とは エラトステネスの篩とは、ある数以下の素数を列挙するアルゴリズムです。 アルゴリズムは単純で、以下の手順で実装できます。 Nの要素をもつbool値配列を作成し、全要素をtrueで初期化する 配列の0番目と1番目の要素をfalseにする(0と1は素数ではないため) 配列の2番目の要素がtrueなら、2を素数として出力する 配列の$2^2$以上の2の倍数番目の要素をすべてfalseにする※ 配列の3番目の要素がtrueなら、3を素数として出力する 配列の$3^2$以上の3の倍数番目の要素をすべてfalseにする 4番目、5番目、・・・、N番目の要素について、同様の処理を繰り返す ※2乗以上の要素をfalseの対象としているのは、2乗より小さい数についてはすでに処理済み(列挙が完了している)であるためです。 Rustでの実装 fn main() { let n = 1000; let mut is_prime = vec![true; n+1]; is_prime[0] = false; is_prime[1] = false; for i in 2..=n { if is_prime[i] { println!("{}", i); let mut j = i * i; while j <= n { is_prime[j] = false; j += i; } } } } 少し高速化版 下記の点を考慮して、少し高速化した実装を行います。 配列の初期化をtrueで初期化するのではなく、falseで初期化する(このほうが高速) 2の倍数は素数ではないので、2の倍数の要素をfalseにする処理を省略 nまでループする必要はなく、nの平方根までの素数を列挙すれば、n以下の素数を列挙できる fn main() { let n = 1000; let mut is_prime = vec!...

rustcをアップデートする方法

rustcをアップデートする方法 下記の一行をコマンドで実行するだけ。 rustup update 出力参考 rustup update info: syncing channel updates for 'stable-x86_64-pc-windows-msvc' warning: Signature verification failed for 'https://static.rust-lang.org/dist/channel-rust-stable.toml' info: latest update on 2023-03-09, rust version 1.68.0 (2c8cc3432 2023-03-06) info: downloading component 'rust-src' info: downloading component 'cargo' info: downloading component 'clippy' info: downloading component 'rust-docs' info: downloading component 'rust-std' info: downloading component 'rustc' 63.9 MiB / 63.9 MiB (100 %) 37.5 MiB/s in 1s ETA: 0s info: downloading component 'rustfmt' info: removing previous version of component 'rust-src' info: removing previous version of component 'cargo' info: removing previous version of component 'clippy' info: removing previous version of component 'rust-docs' info: removing previous version of component 'rust-std' info: removing previous version of component 'rustc' info: removing previous version of component 'rustfmt' info: installing component 'rust-src' info: installing component 'cargo' info: installing component 'clippy' info: installing component 'rust-docs' 19....

Rustの特徴

Rust(ラスト)の特徴 Mozilla が開発を行っている比較的新しいオープンソースなプログラミング言語 ガーベージコレクションがなく、高速でシステムプログラミングに特化した言語 所有権と借用という独特な機構を言語仕様としてもち、メモリ安全性を保証する クロスプラットフォームで動作する Cargo という優秀なパッケージマネージャーを標準で持つ

Rustでシンプルなウィンドウを表示する

Rustでシンプルなウィンドウを表示する [package] name = "win" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies.winapi] version = "0.3" features = ["winuser"] ソースは以下 #![windows_subsystem = "windows"]usewinapi::{um::{winuser::{RegisterClassW,WNDCLASSW,CS_HREDRAW,CS_VREDRAW,LoadIconW,IDI_APPLICATION,LoadCursorW,IDC_ARROW,CreateWindowExW,ShowWindow,SW_NORMAL,UpdateWindow,GetMessageW,TranslateMessage,DispatchMessageW,MSG,WM_DESTROY,PostQuitMessage,DefWindowProcW,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT},wingdi::{GetStockObject,WHITE_BRUSH},},shared::{windef::{HWND,HBRUSH},minwindef::{UINT,WPARAM,LPARAM,LRESULT},},};usestd::ptr;usestd::mem;fn main(){unsafe{letclass_name=encode("my_window_class_name");if!register_wndclass(&class_name){return;}lethwnd=create_window(&class_name);ifhwnd.is_null(){return;}ShowWindow(hwnd,SW_NORMAL);UpdateWindow(hwnd);letmutmsg=mem::uninitialized::<MSG>();loop{ifGetMessageW(&mutmsg,ptr::null_mut(),0,0)==0{return;}TranslateMessage(&mutmsg);DispatchMessageW(&mutmsg);}}}fn encode(source: &str)-> Vec<u16>{source.encode_utf16().chain(Some(0)).collect()}unsafefn register_wndclass(class_name: &[u16])-> bool {letmutwinc=mem::zeroed::<WNDCLASSW>();winc.style=CS_HREDRAW|CS_VREDRAW;winc.lpfnWndProc=Some(win_proc);winc.hIcon=LoadIconW(ptr::null_mut(),IDI_APPLICATION);winc.hCursor=LoadCursorW(ptr::null_mut(),IDC_ARROW);winc.hbrBackground=GetStockObject(WHITE_BRUSHasi32)asHBRUSH;winc.lpszClassName=class_name.as_ptr();RegisterClassW(&winc)>0}unsafefn create_window(class_name: &[u16])-> HWND{CreateWindowExW(0,class_name.as_ptr(),encode("Hello, World!").as_ptr(),WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,0,CW_USEDEFAULT,0,ptr::null_mut(),ptr::null_mut(),ptr::null_mut(),ptr::null_mut(),)}unsafeextern"system"fn win_proc(hwnd: HWND,msg: UINT,w_param: WPARAM,l_param: LPARAM)-> LRESULT{matchmsg{WM_DESTROY=>PostQuitMessage(0),_=>returnDefWindowProcW(hwnd,msg,w_param,l_param),};0}参考 Rust で Windows プログラミング - CreateWindow編

Rustでテストを書く

Rustでテストを書くには、テスト関数の定義の1行上に#[test]属性を付けて関数を作成します。 fn plus(a:i32,b:i32)->i32 {a+b}#[test]fn plus_test(){assert_eq!(plus(1,1),2);}テストコードはcargo testで実行できます。テストが成功するとokと出力されます。 失敗するとFAILEDと出力されます。 成功した場合 C:\Users\admin\Desktop\test1>cargo test Compiling test1 v0.1.0 (C:\Users\admin\Desktop\test1) Finished test [unoptimized + debuginfo] target(s) in 0.35s Running unittests src\main.rs (target\debug\deps\test1-be5d3118bc52cb3a.exe) running 1 test test plus_test ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s 失敗した場合 C:\Users\admin\Desktop\test1>cargo test Compiling test1 v0.1.0 (C:\Users\admin\Desktop\test1) Finished test [unoptimized + debuginfo] target(s) in 0.33s Running unittests src\main.rs (target\debug\deps\test1-be5d3118bc52cb3a.exe) running 1 test test plus_test ....

RustでMessageBoxを表示する

下記の手順でRustでMessageBoxを表示することができます。 Rustをインストールする。 Rustのはじめかた 参照 コマンドプロンプトでcargo new --bin MessageBoxを実行する。 MessageBoxディレクトリに移動する。 Cargo.tomlを開き、下記のように修正する。 [package] name = "hello_world" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] winapi = "0.2.7" user32-sys = "0.2.0" src\main.rsを開き、下記のように修正する。 externcrateuser32;externcratewinapi;usestd::ffi::CString;useuser32::MessageBoxA;usewinapi::winuser::{MB_OK,MB_ICONINFORMATION};fn main(){letlp_text=CString::new("Hello, world!").unwrap();letlp_caption=CString::new("MessageBox Example").unwrap();unsafe{MessageBoxA(std::ptr::null_mut(),lp_text.as_ptr(),lp_caption.as_ptr(),MB_OK|MB_ICONINFORMATION);}} コマンドプロンプトでcargo runを実行する。 リリースのビルドをする場合はcargo build --releaseを実行する。 参考 Hello World MesssageBox example in Rust

Rustで素数を列挙する

Rustで素数を列挙するプログラムを書いてみました。 fn main(){letmax=1000;letmutprimes=vec!...

Rustのはじめかた

はじめに Rustは高速でかつメモリ効率が高いモジュールをモダンな記法で記述できる比較的新しいプログラミング言語です。 マルチプラットフォームに対応しており、WebAssemblyや組み込みの世界でも使われています。 有名なところでは、Firefoxや、DropBox、Cloudflareでも採用されています。 C++の代用としても注目されています。 インストール方法 Rust をインストール 上記サイトから各プラットフォーム向けにインストール方法が公開されています。 初めてのプログラム 次のプログラムをmain.rsとして保存します。 fn main() { println!("Hello, world!"); } コマンドプロンプトまたはターミナルからrustc main.rsを実行すると、 コンパイルされ、./main(Windowsの場合はmain.exe)を実行するとHello, world!と出力されます。 日本語ドキュメント The Rust Programming Language 日本語版 Rustを学ぶうえで必要となる解説は上記のリンク(日本語訳版)に集約されています。 Rustのテキストを購入する必要がないくらい充実しています。 Webで動かしてみたい場合 コンパイラをインストールせずにWebで動かしてみたい場合は The Rust Playground が使えます。 コードを入力して「実行ボタン」を押すと、Web上でコンパイルされ実行されます。