Joseph Jude

Technology, Psychology, and Story Telling

Sum of even valued Fibonacci numbers less than 4 million

Posted: Tags: code,euler,swift,tsc,python

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.



Like the post? Retweet it. Got comments? Reply.

Comments

comments powered by Disqus