欢迎使用CSDN-markdown编辑器

来源:互联网 发布:淘宝无线端装修链接 编辑:程序博客网 时间:2024/06/05 20:56

Project Euler题解(Problem 2)

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

这道题就是求不超过400万的所有偶斐波那契数的和。很简单。代码如下,主要是通过实现rust胡Iterator Trait来迭代的求出斐波那契数。

#![feature(core)]use std::iter::Iterator;// #[derive(Copy)]struct Fibonacci {    a: u32,    b: u32,}impl Fibonacci {    fn new() -> Fibonacci {        Fibonacci{a:0, b:1}    }}impl Iterator for Fibonacci {    type Item = u32;    fn next(&mut self) -> Option<u32> {        let result = self.a + self.b;        self.a = self.b;        self.b = result;        Some(result)    }}fn solve() -> u32 {    Fibonacci::new().take_while(|&x| x < 4000_000).filter(|&x| x % 2 == 0).sum()    }
0 0