-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.rs
33 lines (26 loc) · 978 Bytes
/
2.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
Problem 2 - Even Fibonacci numbers
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.
*/
use rayon::prelude::*;
fn fibonacci(upper_bound: usize) -> Vec<usize> {
// F_0 = 1, F_1 = 2
let mut sequence = vec![1, 2];
// F_n = F_(n - 1) + F_(n - 2)
while sequence[sequence.len() - 1] < upper_bound {
let new_value = sequence[sequence.len() - 1] + sequence[sequence.len() - 2];
sequence.push(new_value);
}
return sequence;
}
pub fn main() {
let sequence = fibonacci(4000000);
let even = sequence.par_iter().filter(|n| *n % 2 == 0);
let sum: usize = even.sum();
print!(
"The sum of the first 4000000 even fibonacci numbers is {}",
sum
);
}