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.
function sumEvenFibonacci(num: number): number {
let sum: number = 0;
let fibonacci: number[] = [1, 2];
while (fibonacci[fibonacci.length - 1] < num) {
fibonacci.push(fibonacci[fibonacci.length - 1] + fibonacci[fibonacci.length - 2]);
}
for (let i: number = 0; i < fibonacci.length; i++) {
if (fibonacci[i] % 2 === 0) {
sum += fibonacci[i];
}
}
return sum;
}
Thoughts:
I had previously solved this one myself and its interesting to see how copilot's solution differs, using a while loop to get the numbers and then using a for loop to get the even numbers.