diff --git a/src/algorithms/math/fibonacci.js b/src/algorithms/math/fibonacci.js new file mode 100644 index 00000000..a4a49196 --- /dev/null +++ b/src/algorithms/math/fibonacci.js @@ -0,0 +1,32 @@ +// Function takes in an integer n, generates an array of the first n Fibonacci numbers, and calculates their sum +function fibonacciSum(n) { + if (n <= 0) { + return { sum: 0, sequence: [] }; + } + + const fibonacciSequence = [0]; + + if (n === 1) { + return { sum: 0, sequence: fibonacciSequence }; + } + + fibonacciSequence.push(1); + + for (let i = 2; i < n; i++) { + const nextNumber = fibonacciSequence[i - 1] + fibonacciSequence[i - 2]; + fibonacciSequence.push(nextNumber); + } + + const sum = fibonacciSequence.reduce((acc, num) => acc + num, 0); + + return { sum, sequence: fibonacciSequence }; +} + +/* +For testing purposes, change the value of integer n below +const n = 7; +*/ +const result = fibonacciSum(n); + +console.log(`Sum of the first ${n} Fibonacci numbers:`, result.sum); +console.log(`Fibonacci sequence:`, result.sequence); diff --git a/src/algorithms/math/prime.js b/src/algorithms/math/prime.js new file mode 100644 index 00000000..efb32c6f --- /dev/null +++ b/src/algorithms/math/prime.js @@ -0,0 +1,25 @@ +// Function takes in an integer n and tells the user whether or not it is a prime number +function isPrime(n) { + if (n <= 1) { + return false; + } + + for (let i = 2; i <= Math.sqrt(n); i++) { + if (n % i === 0) { + return false; + } + } + + return true; +} + +/* +For testing purposes, change the value of integer inputNumber +const inputNumber = 23; +*/ + +if (isPrime(inputNumber)) { + console.log(`${inputNumber} is a prime number.`); +} else { + console.log(`${inputNumber} is not a prime number.`); +}