I'm trying to solve problem 2 of Project Euler:
"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."
When running the code it keeps stating EXC_BAD_INSTRUCTION. It seems this is due to the enormous number that it tries to sum when getting to the 4 million terms.
I have tried both a for in loop as well as a while in loop. See the code (also parts in comments for prior attempt)
func sumFibonacci(until n:Int) {
var num1 = 0
var num2 = 1
var sumEven = 0
var number = 0
// Attempted with for in loop - crashed
// for _ in 1...n {
// let sum = num1+num2
// num1 = num2
// num2 = sum
//
// if sum % 2 == 0 {
// sumEven += sum
// }
while number < n {
let sum = num1+num2
num1 = num2
num2 = sum
if sum % 2 == 0 {
sumEven += sum
}
number += 1
}
print("Sum even terms are \(sumEven)")
}
sumFibonacci(until: 4000000)
I would expect a result (either right or wrong), but I keep getting the stated error.