Project Euler Problems for Learn Programming - Solution 2 (Python & Javascript)

shutterstock-programming.jpg

Hey SteemIt community. Did you heard about Project Euler? If you don't know please review this website: Project Euler

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.

Solution (Python)

fibonacci = [2]
a = 1
b = 2
c = a+b
while c < 4000000:
    if c%2==0:
        fibonacci.append(c)
    a = b
    b = c
    c = a+b
print(sum(fibonacci))

Solution (Javascript)

fibonacci = [2];
firstNum = 1;
secondNum = 2;
sumNum = firstNum + secondNum;
while (sumNum < 4000000) {
    if (sumNum % 2 == 0) {
        fibonacci.push(sumNum);
    }
    firstNum = secondNum;
    secondNum = sumNum;
    sumNum = firstNum + secondNum;
}
console.log(fibonacci.reduce((a, b) => a + b, 0))

Result: 4613732

Project Euler - Solution 1

Project Euler - Solution 3

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center