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));
}
이 예제의 실행 버튼 만들기 코드 실행 결과
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
97 is prime: true

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Strings: String and &str →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지