Rust 연습 문제

Fibonacci Sequence in Rust

Build the Fibonacci numbers with a loop, a tuple swap and a vector.

  • 초급
  • 2분 분량
  • 실행 가능한 예제 1개
배울 내용
  • A loop with two variables
  • (a, b) = (b, a + b)
  • Why u64
The first numbers
00
11
12
23
34
55
5 = 2 + 3

Each number is the sum of the two before

Each Fibonacci number is the sum of the two before it, starting from 0 and 1. Build the first numbers of the sequence in a vector.

a and b hold two neighbouring numbers. (a, b) = (b, a + b) moves both one step forward in a single assignment. u64 is used because Fibonacci numbers grow quickly: the 50th no longer fits in 32 bits.

핵심 포인트

  1. Start from 0 and 1.
  2. One tuple assignment moves both values.
  3. u64 holds much larger numbers than u32.

실행 가능한 Rust 예제

Rust
코드 실행 →
main.rs
fn fibonacci(count: usize) -> Vec<u64> {
    let mut sequence = Vec::with_capacity(count);
    let (mut a, mut b) = (0u64, 1u64);
    for _ in 0..count {
        sequence.push(a);
        (a, b) = (b, a + b);
    }
    sequence
}

fn main() {
    println!("{:?}", fibonacci(10));
    println!("50th: {}", fibonacci(50)[49]);
}
이 예제의 실행 버튼 만들기 코드 실행 결과
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
50th: 7778742049

연습

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

이 레슨을 마쳤나요?

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

다음: Functions and Return Values →

챌린지로 연습하기

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

모든 챌린지