Total Pageviews

Friday, January 1, 2021

Project Euler - Rust Problem 2

 https://projecteuler.net/problem=2

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.


Fibonacci sequences have always given me trouble.

The basic idea is that you are dealing with 3 terms at a time.

to start = 0,1,1

the first term 0 plus the second term 1 is equal to the third term 1.  Then we can move those along.  

If a is equal to the first term, b is equal to the second term, c is equal to the third term.  Now we have variables with names.

So we let mut a = 0;

let mut b = 1;

let mut c = 1;


To move through the terms, we need a loop of some kind.  We could use a for loop if we knew how many terms we would go through.  Since this isn't known, we ditch the for loop.  

Since the problem is giving us an upper limit, a while or do until loop would work great.  There is no do until loop in rust.  That leaves the while loop.

While c (the furthest term) is less than 4 million, do this code.

Here we can implement the basic logic needed to run through the Fibonacci sequence. I'm just glad that I don't have to store the values then go through them.  That would make this a bit more complex.

Loop

In the loop, we can just set a equal to b, b equal to c, and then c equal to a + b.  

This logic only goes through the sequence until c is greater than the upper limit.  


But that doesn't do anything.

Sum will still = 0.


We have to add c to the sum value.  But not every time.  only IF it's even, aka evenly divisible by 2.

So we add the if c % 2== 0{ sum += c;} logic and now all is right with the world.

 

fn main() {


    let mut sum: i32 = 0;

    let mut a: i32 = 0;

    let mut b: i32 = 1;

    let mut c: i32 = 1;

    

    while c < 4000000{

        a = b;

        b = c;

        c = a + b;

        if c %2 == 0{

            sum += c;

        }

        

    } 

    println!("{}", sum);

}

run time 1.05 seconds.


I would compare the other answers but honestly there's only one other rust answer it is very long and a bit complicated for reasons... I don't really understand.  I also couldn't get it to run in the playground.

I'm sure there are other ways to approach this.  I'm sure this isn't the greatest way to handle this.  We'll see, the more I learn.

No comments: