แบบฝึกหัด Rust

Prime Numbers in Rust

Test whether a number is prime and list the primes up to 30 with filter.

  • ระดับเริ่มต้น
  • อ่าน 2 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • 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.

ประเด็นสำคัญ

  1. Numbers below 2 are not prime.
  2. Divisors up to the square root are enough.
  3. 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));
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
97 is prime: true

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Strings: String and &str →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด