Rust 練習問題
Prime Numbers in Rust
Test whether a number is prime and list the primes up to 30 with filter.
学べること
- Trial division
- Stopping at the square root
- filter on a range
2 to 7
2prime
3prime
42 x 2
5prime
62 x 3
7prime
Only divisible by 1 and itself
A prime number is larger than 1 and can only be divided by 1 and itself. Write a function that tests one number, then use it to filter a range.
It is enough to try divisors up to the square root of n, which is what divisor * divisor <= n checks. filter keeps the numbers for which is_prime returns true and collect gathers them into a vector.
重要なポイント
- Numbers below 2 are not prime.
- Divisors up to the square root are enough.
- filter keeps the numbers that pass the test.
実行できる Rust のサンプル
Rust
main.rs
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
let mut divisor = 2;
while divisor * divisor <= n {
if n % divisor == 0 {
return false;
}
divisor += 1;
}
true
}
fn main() {
let primes: Vec<u32> = (1..=30).filter(|&n| is_prime(n)).collect();
println!("{:?}", primes);
println!("97 is prime: {}", is_prime(97));
}
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
97 is prime: true練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- 素数判定 数が素数かどうかを判定してください。 簡単
- List Primes With a Sieve Find primes up to a limit by marking composite multiples. 中級