mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 07:01:18 +08:00
Add Algorithms.
This commit is contained in:
parent
b9bcdbb987
commit
0d6aba1078
8
src/algorithms/fibonacci/README.md
Normal file
8
src/algorithms/fibonacci/README.md
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
# Fibonacci Number
|
||||||
|
|
||||||
|
In mathematics, the Fibonacci numbers are the numbers in the following
|
||||||
|
integer sequence, called the Fibonacci sequence, and characterized by
|
||||||
|
the fact that every number after the first two is the sum of the two
|
||||||
|
preceding ones:
|
||||||
|
|
||||||
|
`0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...`
|
15
src/algorithms/fibonacci/__test__/fibonacci.test.js
Normal file
15
src/algorithms/fibonacci/__test__/fibonacci.test.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import fibonacci from '../fibonacci';
|
||||||
|
|
||||||
|
describe('fibonacci', () => {
|
||||||
|
it('should calculate fibonacci correctly', () => {
|
||||||
|
expect(fibonacci(1)).toBe(1);
|
||||||
|
expect(fibonacci(2)).toBe(1);
|
||||||
|
expect(fibonacci(3)).toBe(2);
|
||||||
|
expect(fibonacci(4)).toBe(3);
|
||||||
|
expect(fibonacci(5)).toBe(5);
|
||||||
|
expect(fibonacci(6)).toBe(8);
|
||||||
|
expect(fibonacci(7)).toBe(13);
|
||||||
|
expect(fibonacci(8)).toBe(21);
|
||||||
|
expect(fibonacci(20)).toBe(6765);
|
||||||
|
});
|
||||||
|
});
|
26
src/algorithms/fibonacci/fibonacci.js
Normal file
26
src/algorithms/fibonacci/fibonacci.js
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
// Calculate fibonacci number at specific position using Dynamic Programming approach.
|
||||||
|
export default function fibonacci(numberPosition) {
|
||||||
|
if (numberPosition === 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let iterationsCounter = numberPosition - 1;
|
||||||
|
|
||||||
|
// Calculated fibonacci number.
|
||||||
|
let fib = null;
|
||||||
|
// Previous fibonacci number.
|
||||||
|
let fibPrev = 1;
|
||||||
|
// Before previous fibonacci number.
|
||||||
|
let fibPrevPrev = 0;
|
||||||
|
|
||||||
|
while (iterationsCounter) {
|
||||||
|
// Calculate current value using two previous ones.
|
||||||
|
fib = fibPrev + fibPrevPrev;
|
||||||
|
// Shift previous values.
|
||||||
|
fibPrevPrev = fibPrev;
|
||||||
|
fibPrev = fib;
|
||||||
|
iterationsCounter -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fib;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user