๊ด€๋ฆฌ ๋ฉ”๋‰ด

IT’s Portfolio

[Rust] Start Rust (Day 8) - Rust Example Script 2 [Nth in Fibonacci Sequence] ๋ณธ๋ฌธ

Development Study/Rust

[Rust] Start Rust (Day 8) - Rust Example Script 2 [Nth in Fibonacci Sequence]

f1r3_r41n 2023. 1. 18. 14:38
728x90
๋ฐ˜์‘ํ˜•

๐Ÿฆ€ Rust Day 8

๐Ÿณ๏ธ Rust Example Script 2 - Nth in Fibonacci Sequence

1๏ธโƒฃ Description

  • ์กฐ๊ฑด 0<=n<=45 ์— ๋ถ€ํ•ฉํ•˜๋Š” ์ •์ˆ˜ n์„ ์ž…๋ ฅ๋ฐ›์•„ n๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ ์ž‘์„ฑ

2๏ธโƒฃ how it works

  • ์กฐ๊ฑด 0<=n<=45 ์— ๋ถ€ํ•ฉํ•˜๋Š” ์ •์ˆ˜ n์„ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.
  • n๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์„ ์ถœ๋ ฅํ•œ๋‹ค.

3๏ธโƒฃ Code

use std::io;

fn simple_fibo(n: u32) -> u64 {
    let mut a = 0;
    let mut b = 1;

    if n <= 1 {
        return n.into();
    }

    for _ in 0..n-1 {
        let tmp = a;
        a = b;
        b = tmp+b;
    }
    return b;
}

fn array_fibo(n: u32) -> usize {
    let mut fibo_arr: [usize; 2] = [0, 1];
    let n: usize = n.try_into().unwrap();

    for i in fibo_arr.len()..n+1 {
        fibo_arr[i%2] = fibo_arr[(n-1)%2] + fibo_arr[(n-2)%2];
    }

    return fibo_arr[n%2]
}

fn recursive_fibo(n: u32) -> u64 {
    if n <= 1 {
        return n.into();
    } else {
        return recursive_fibo(n-1) + recursive_fibo(n-2);
    }
}

fn main() {
    loop {
        let mut number = String::new();

        io::stdin().read_line(&mut number)
            .expect("Unable to read input!");

        let number: u32 = match number.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Error! You have to input number!");
                continue
            },
        };

        println!("Simple Fibonacci Sequence: {}", simple_fibo(number));
        println!("Recursive Fibonacci Sequence: {}", recursive_fibo(number));
        println!("Array Fibonacci Sequence: {}", array_fibo(number));
        break;
    }
}

4๏ธโƒฃ Result

  • n: 15
      15 // input
      Simple Fibonacci Sequence: 610 // output
      Recursive Fibonacci Sequence: 610 // output
      Array Fibonacci Sequence: 610 // output
  • n: 44
      44 // input
      Simple Fibonacci Sequence: 701408733 // output
      Recursive Fibonacci Sequence: 701408733 // output
      Array Fibonacci Sequence: 701408733 // output

5๏ธโƒฃ Reference

  • Febonacci Sequence in Python
    • https://it-neicebee.tistory.com/150
    • ์ด ๊ธ€์˜ ์žฌ๊ท€์  ๋™์  ๊ณ„ํš๋ฒ• ๋ฐ ํ–‰๋ ฌ ์—ฐ์‚ฐ ์— ๋Œ€ํ•œ Rust ๊ตฌํ˜„์€ ํ•„์ž์˜ Rust ์ˆ™๋ จ๋„ ๋ถ€์กฑ์œผ๋กœ ๊ตฌํ˜„ํ•˜์ง€ ๋ชปํ–ˆ์Œ. ์•ž์œผ๋กœ ๋” ๊ณต๋ถ€ํ•ด์„œ ํ•ด๋‹น ๋ฐฉ๋ฒ•์„ Rust๋กœ ๊ตฌํ˜„ํ•ด๋ณด๋Š” ๊ธ€์„ ์—…๋กœ๋“œํ•  ์˜ˆ์ •์ž„.
  • Rust official Document about core::convert::Into
  • Rust official Document about core::convert::TryInto
728x90
๋ฐ˜์‘ํ˜•
Comments