Skip to content

Commit 3d30069

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank]: Project Euler #2: Even Fibonacci numbers solved ✓
1 parent 1621860 commit 3d30069

File tree

3 files changed

+95
-0
lines changed

3 files changed

+95
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# [Even Fibonacci numbers](https://www.hackerrank.com/contests/projecteuler/challenges/euler002)
2+
3+
- Difficulty: #easy
4+
- Category: #ProjectEuler+
5+
6+
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
7+
By starting with $ 1 $ and $ 2 $, the first $ 10 $ terms will be:
8+
9+
$$ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 $$
10+
11+
By considering the terms in the Fibonacci sequence whose values do not exceed
12+
$ N $, find the sum of the even-valued terms.
13+
14+
## Input Format
15+
16+
First line contains $ T $ that denotes the number of test cases. This is
17+
followed by $ T $ lines, each containing an integer, $ N $.
18+
19+
## Constraints
20+
21+
- $ 1 \leq T \leq 10^5 $
22+
- $ 10 \leq N \leq 4 × 10^{16} $
23+
24+
## Output Format
25+
26+
Print the required answer for each test case.
27+
28+
## Sample Input 0
29+
30+
```text
31+
2
32+
10
33+
100
34+
```
35+
36+
## Sample Output 0
37+
38+
```text
39+
10
40+
44
41+
```
42+
43+
## Explanation 0
44+
45+
- For $ N = 10 $, we have $ \{2, 8\} $, sum is $ 10 $.
46+
47+
- For $ N = 100 $, we have $ \{2, 8, 34 \} $, sum is $ 44 $.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { describe, expect, it } from '@jest/globals';
2+
import { logger as console } from '../../logger';
3+
4+
import { euler002 } from './euler002';
5+
6+
describe('euler002', () => {
7+
it('euler002 Test case 0', () => {
8+
expect.assertions(2);
9+
10+
const tests = [
11+
{ n: 10, answer: 10 },
12+
{ n: 100, answer: 44 }
13+
];
14+
15+
tests.forEach((test) => {
16+
const calculated = euler002(test.n);
17+
console.log(`euler002(${test.n}) solution found: ${test.answer}`);
18+
expect(calculated).toStrictEqual(test.answer);
19+
});
20+
});
21+
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @link Problem definition [[docs/hackerrank/projecteuler/euler001.md]]
3+
*/
4+
5+
export function fibo_even_sum(n: number): number {
6+
let total = 0;
7+
let fibo = 0;
8+
let fibo1 = 1;
9+
let fibo2 = 1;
10+
11+
while (fibo1 + fibo2 < n) {
12+
fibo = fibo1 + fibo2;
13+
fibo1 = fibo2;
14+
fibo2 = fibo;
15+
16+
if (fibo % 2 == 0) {
17+
total += fibo;
18+
}
19+
}
20+
21+
return total;
22+
}
23+
24+
// Function to find the sum of all multiples of a and b below n
25+
export function euler002(n: number): number {
26+
return fibo_even_sum(n);
27+
}

0 commit comments

Comments
 (0)