Skip to content

Commit

Permalink
Merge pull request #14 from sir-gon/feature/problem0002
Browse files Browse the repository at this point in the history
Problem 0002: solved.
  • Loading branch information
sir-gon authored May 15, 2023
2 parents 063eb0a + 3fbcc24 commit fa20364
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/problem0002.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Even Fibonacci numbers
*
* https://projecteuler.net/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.
*/

import logger from './logger';

import { problem0002 } from './problem0002';

describe('problem 0002', () => {
it('problem 0002 solution found', () => {
expect.assertions(1);

const solutionFound = 4613732;
const top = 4000000;

const calculated = problem0002(top);

logger.info(`PROBLEM 0002 solution found: ${calculated}`);

expect(calculated).toBe(solutionFound);
});
});
43 changes: 43 additions & 0 deletions src/problem0002.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Even Fibonacci numbers
*
* https://projecteuler.net/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.
*/

import logger from './logger';

export function problem0002(_top: number) {
let i = 0;
let last1 = 1;
let last2 = 0;
let evenSum = 0;

let fibo = 0;
do {
fibo = last2 + last1;

logger.debug(`Fibonacci (${i}) = ${fibo}`);

if (fibo % 2 === 0) {
evenSum += fibo;
}

// next keys:
last2 = last1;
last1 = fibo;
i += 1;
} while (fibo < _top);

logger.info(`RESULT = ${evenSum}`);
return evenSum;
}

export default { problem0002 };

0 comments on commit fa20364

Please sign in to comment.