Skip to content

Instantly share code, notes, and snippets.

@clecidor
Last active July 27, 2018 05:09
Show Gist options
  • Save clecidor/b766bc2e0ef0fac3a785bb3da3e3ebec to your computer and use it in GitHub Desktop.
Save clecidor/b766bc2e0ef0fac3a785bb3da3e3ebec to your computer and use it in GitHub Desktop.
sum_even_fibonacci.js - Find the sum-total of even Fibonacci numbers
/**
* Find the sum-total of even Fibonacci numbers
*
* @param max - (integer) that specifies the maximum term to count up to (cannot exceed 4 million)
*
* Example:
* sum_even_fibonacci(2) -> 2
* sum_even_fibonacci(8) -> 10
* sum_even_fibonacci(34) -> 44
*/
function sum_even_fibonacci(max) {
// Ensure max does not exceed 4 million
var LIMIT = 4000000;
max = parseInt(max < LIMIT ? max : LIMIT) || 0;
// Start with intial two Fibonacci terms
var prev_term = 1;
var current_term = 2;
var next_term;
var total = 0;
// While current-term is within max
while (current_term <= max) {
// If the current_term is even, add it to the total
if (current_term % 2 == 0) {
total += current_term;
}
// Calculate the next-term's value by adding previous-term to current-term
next_term = prev_term + current_term;
// Update previous-term with the current-term's value
prev_term = current_term;
// Update current-term with the next-term's value
current_term = next_term;
}
return total;
}
module.exports = sum_even_fibonacci;
var sum_even_fibonacci = require('./sum_even_fibonacci');
test('sum_even_fibonacci(0) should equal 0', () => {
expect(sum_even_fibonacci(0)).toBe(0);
});
test('sum_even_fibonacci(1) should equal 0', () => {
expect(sum_even_fibonacci(1)).toBe(0);
});
test('sum_even_fibonacci(2) should equal 2', () => {
expect(sum_even_fibonacci(2)).toBe(2);
});
test('sum_even_fibonacci(3) should equal 2', () => {
expect(sum_even_fibonacci(3)).toBe(2);
});
test('sum_even_fibonacci(4) should equal 2', () => {
expect(sum_even_fibonacci(4)).toBe(2);
});
test('sum_even_fibonacci(5) should equal 2', () => {
expect(sum_even_fibonacci(5)).toBe(2);
});
test('sum_even_fibonacci(8) should equal 10', () => {
expect(sum_even_fibonacci(8)).toBe(10);
});
test('sum_even_fibonacci(9) should equal 10', () => {
expect(sum_even_fibonacci(9)).toBe(10);
});
test('sum_even_fibonacci(10) should equal 10', () => {
expect(sum_even_fibonacci(10)).toBe(10);
});
test('sum_even_fibonacci(34) should equal 44', () => {
expect(sum_even_fibonacci(34)).toBe(44);
});
test('sum_even_fibonacci(35) should equal 44', () => {
expect(sum_even_fibonacci(35)).toBe(44);
});
test('sum_even_fibonacci(36) should equal 44', () => {
expect(sum_even_fibonacci(36)).toBe(44);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment