init
This commit is contained in:
6
problems/p2/Cargo.toml
Normal file
6
problems/p2/Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "p2"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
48
problems/p2/src/main.rs
Normal file
48
problems/p2/src/main.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
struct Fib {
|
||||
current: u32,
|
||||
next: u32,
|
||||
}
|
||||
|
||||
impl Fib {
|
||||
fn new() -> Fib {
|
||||
Fib {
|
||||
current: 1,
|
||||
next: 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Fib {
|
||||
type Item = u32;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let current = self.current;
|
||||
self.current = self.next;
|
||||
self.next += current;
|
||||
Some(current)
|
||||
}
|
||||
}
|
||||
|
||||
fn fib_sum() -> u32 {
|
||||
let mut sum: u32 = 0;
|
||||
let mut fib = Fib::new();
|
||||
|
||||
let mut number = fib.next().unwrap();
|
||||
while number < 4000000 {
|
||||
if number % 2 == 0 {
|
||||
sum += number;
|
||||
}
|
||||
|
||||
number = fib.next().unwrap();
|
||||
}
|
||||
|
||||
sum
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut fib = Fib::new();
|
||||
|
||||
for _ in 0..10 {
|
||||
print!("{} ", fib.next().unwrap());
|
||||
}
|
||||
println!("{}", fib_sum());
|
||||
}
|
||||
Reference in New Issue
Block a user