rust 구현 Fibonacci 수열

7777 단어 Rust

for 순환 실현

fn main() {
    let mut v = vec![1,1];
    let n = 12;
    for i in 2..n {
        let tmp = v[(i-1) as usize] + v[(i-2) as usize];
        v.push(tmp);
    }
    assert_eq!(v, vec![1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]);
}

귀속 방식 실현

fn fun(mut v: Vec<i32>, n: usize, i: usize) -> Vec<i32>{
    match i < n {
        true => {
            let tmp = v[i-1] + v[i-2];
            v.push(tmp);
            return fun(v, n, i+1);
        }
        _ => {
            return v;
        }
    }
}
fn main() {
    let mut v = vec![1,1];
    let n = 12;
    v = fun(v, n, 2);
    assert_eq!(v, vec![1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]);
}

좋은 웹페이지 즐겨찾기