mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-14 18:03:53 +08:00

* Add prettier config * test: add test to check for absolute function * chore: es5 to es6 * test: add test to check mean function * test: add test for sum of digit * test: add test for factorial * test: add test for fibonnaci * test: add test for find HCF * test: add test for lcm * test: add gridget test * test: add test for mean square error * test: add test for modular binary exponentiation * test: add tests for palindrome * test: add test for pascals triangle * test: add tests for polynomial * test: add tests for prime check * test: add tests for reverse polish notation * test: add tests for sieve of eratosthenes * test: add tests for pi estimation monte carlo method * chore: move tests to test folder * chore: fix standardjs errors
76 lines
1.8 KiB
JavaScript
76 lines
1.8 KiB
JavaScript
const list = []
|
|
|
|
const FibonacciIterative = (nth) => {
|
|
const sequence = []
|
|
|
|
if (nth >= 1) sequence.push(1)
|
|
if (nth >= 2) sequence.push(1)
|
|
|
|
for (let i = 2; i < nth; i++) {
|
|
sequence.push(sequence[i - 1] + sequence[i - 2])
|
|
}
|
|
|
|
return sequence
|
|
}
|
|
|
|
const FibonacciRecursive = (number) => {
|
|
return (() => {
|
|
switch (list.length) {
|
|
case 0:
|
|
list.push(1)
|
|
return FibonacciRecursive(number)
|
|
case 1:
|
|
list.push(1)
|
|
return FibonacciRecursive(number)
|
|
case number:
|
|
return list
|
|
default:
|
|
list.push(list[list.length - 1] + list[list.length - 2])
|
|
return FibonacciRecursive(number)
|
|
}
|
|
})()
|
|
}
|
|
|
|
const dict = new Map()
|
|
|
|
const FibonacciRecursiveDP = (stairs) => {
|
|
if (stairs <= 0) return 0
|
|
if (stairs === 1) return 1
|
|
|
|
// Memoize stair count
|
|
if (dict.has(stairs)) return dict.get(stairs)
|
|
|
|
const res =
|
|
FibonacciRecursiveDP(stairs - 1) + FibonacciRecursiveDP(stairs - 2)
|
|
|
|
dict.set(stairs, res)
|
|
|
|
return res
|
|
}
|
|
|
|
// Algorithms
|
|
// Calculates Fibonacci(n) such that Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2)
|
|
// Fibonacci(0) = Fibonacci(1) = 1
|
|
// Uses a bottom up dynamic programming approach
|
|
// Solve each sub-problem once, using results of previous sub-problems
|
|
// which are n-1 and n-2 for Fibonacci numbers
|
|
// Although this algorithm is linear in space and time as a function
|
|
// of the input value n, it is exponential in the size of n as
|
|
// a function of the number of input bits
|
|
// @Satzyakiz
|
|
|
|
const FibonacciDpWithoutRecursion = (number) => {
|
|
const table = []
|
|
table.push(1)
|
|
table.push(1)
|
|
for (var i = 2; i < number; ++i) {
|
|
table.push(table[i - 1] + table[i - 2])
|
|
}
|
|
return table
|
|
}
|
|
|
|
export { FibonacciDpWithoutRecursion }
|
|
export { FibonacciIterative }
|
|
export { FibonacciRecursive }
|
|
export { FibonacciRecursiveDP }
|