Skip to content

Instantly share code, notes, and snippets.

@ranjanprj
Created May 2, 2017 07:00
Show Gist options
  • Save ranjanprj/50bd27673586ac10659600dc13dc17cb to your computer and use it in GitHub Desktop.
Save ranjanprj/50bd27673586ac10659600dc13dc17cb to your computer and use it in GitHub Desktop.
/*
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.
*** PROBLEM WITH EULER CONDITION THEY SAY 4 MILLION BUT ACTUALLY MEAN 40 MILLION
*/
fn fibonacci(limit : i32) -> Vec<i32> {
let mut i = 1;
let mut j = 2;
let mut fibs = vec![1,2];
println!("{}",limit);
loop{
let next_fib = i+j;
if next_fib > limit {
break;
}
fibs.push(next_fib);
i = j;
j = next_fib;
}
fibs
}
fn sum_even_fibs(v : Vec<i32> ) -> i32 {
let mut sum = 0;
for i in v {
if i % 2 == 0 {
sum += i;
}
}
sum
}
fn main(){
let fib = fibonacci(4000000);
println!("{:?}",fib);
let sum = sum_even_fibs(fib);
println!("{}",sum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment