Joseph Jude

Sum of even valued Fibonacci numbers less than 4 million

2016.05.02 / code / euler / swift / tsc / python /

Solution to Project Euler 002 problem in Swift, Python & Typescript

What I learnt (WIL): tuple assignment

Python

answer = 0
current_fibonacci = 1
next_fibonacci = 2

while current_fibonacci <= 4000000:
  if current_fibonacci % 2 == 0:
    answer += current_fibonacci
  # generate the next numbers
  current_fibonacci, next_fibonacci = next_fibonacci, current_fibonacci + next_fibonacci

print answer
# 4613732

Typescript

var answer = 0;
var current_fibonacci = 1
var next_fibonacci = 2

while (current_fibonacci <= 4000000) {
  if (current_fibonacci % 2 == 0) {
    answer += current_fibonacci;
  }
  [current_fibonacci, next_fibonacci] = [next_fibonacci, current_fibonacci + next_fibonacci]
}
console.log(answer)
// 4613732

Swift

var answer = 0
var currentFibonacci = 1
var nextFibonacci = 2

while currentFibonacci <= 4000000 {
  if currentFibonacci % 2 == 0 {
    answer += currentFibonacci
  }
  (currentFibonacci, nextFibonacci) = (nextFibonacci, currentFibonacci + nextFibonacci)
}
print(answer)
// 4613732

Git Repository / All Euler Solutions

Got comments? Tweet it, or comment below.


Share this post on

Twitter | | |