Friday, February 26, 2021

Project euler #2

 /*https://projecteuler.net/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.


Analysis:

    2                    8                               34                       144

  1 2 (1+2) (1+2*2) (1*2 + 2*3) (1*3+2*5) (1*5+2*8) (1*8+2*13) (13, 21) (21 34) (34,55)

    x                    x                              x                          x


So,

each even number is represented as P=1*a + 2*b

next even number is P_next=1*p + 2*(2a+3b)


It's trivial to write program with above fomular

*/

#include <iostream>

int main()

{

    unsigned int a=0, b=1, i = 2, sum = 0;

    unsigned int nextA, nextB;

    

    while (i <= 4000000)

    {

        sum += i;

        nextB = 2*a + 3*b;

        nextA = i;

        i = 1*nextA + 2*nextB;

        a = nextA;

        b = nextB;

    }


    std::cout << "sum: " << sum << std::endl;

    return sum; 

}


Project euler #1

 https://projecteuler.net/problem=1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.


Find the sum of all the multiples of 3 or 5 below 1000.

A:

sum of multiples of 3: 3, 6, ... 999 = 333*(1+333)*3/2=166833

sum of multiples of 5: 5, 10, ... 5*199 = 199*(1+199)*5/2=99500

sum of multiples of 15: 15, 30, ... 66*15 = 66*(66+1)*15/2=33165

Final sum: 166833+99500-33165=233168