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

in javascript •  7 years ago  (edited)

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

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond Please consider upvoting this comment as this project is supported only by your upvotes!