0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rust でオイラープロジェクト2

Posted at

まずは逐次型で書いた場合。

fn create_fibonacci_sequence(n: i32) -> Vec<i32> {
    let mut a = 0;
    let mut b = 1;
    let mut fib = a + b;
    let mut sequence = vec![a, b];

    while fib < n {
        a = b;
        b = fib;
        fib = a + b;
        sequence.push(fib);
    }
    sequence
}

pub fn solver(n: i32) -> i32 {
    create_fibonacci_sequence(n)
        .iter()
        .filter(|&x| x % 2 == 0)
        .sum()
}

つぎに宣言型で書いた場合。

struct Fibonacci {
    a: i32,
    b: i32,
}

impl Fibonacci {
    fn new() -> Self {
        Self { a: 0, b: 1 }
    }
}

impl Iterator for Fibonacci {
    type Item = i32;
    fn next(&mut self) -> Option<Self::Item> {
        let next = self.b + self.a;
        self.a = self.b;
        self.b = next;
        Some(next)
    }
}

pub fn solver(n: i32) -> i32 {
    Fibonacci::new()
        .take_while(|&x| x < n)
        .filter(|&x| x % 2 == 0)
        .sum()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?