欢迎使用CSDN-markdown编辑器
2015-06-09 09:57
696 查看
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() }
相关文章推荐
- Rust 与开发环境的安装与设置(Windows篇)
- 编译Rust for arm
- 使用Rust交叉编译arm程序
- Project Euler题解(Problem 1)
- Project Euler 40
- [Project Euler]Problem 1:Multiples of 3 and 5
- 1.介绍
- 2.开始
- 3.基本语法
- 4.控制结构
- 欧拉回路及其简单应用
- Problem 40—Champernowne's constant
- Problem 39—Integer right triangles
- Problem 37—Truncatable primes
- Problem 35—Circular primes
- Problem 30—Digit fifth powers
- Problem 34—Digit factorials
- 安装Rust
- 第一个Rust程序——Hello,world!
- Rust的包管理器Cargo