From 2f8956cc562fc773f295760a4a24b1f326c1429c Mon Sep 17 00:00:00 2001 From: ethanpoyton Date: Sun, 22 Dec 2024 07:48:20 -0500 Subject: [PATCH 1/2] Created fibonacci.js Function takes in an integer n, generates an array of the first n Fibonacci numbers, and calculates their sum --- src/algorithms/math/fibonacci.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/algorithms/math/fibonacci.js 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); From 722286edf1c9836ff04435b9245d918d7c274e72 Mon Sep 17 00:00:00 2001 From: ethanpoyton Date: Sun, 22 Dec 2024 08:02:21 -0500 Subject: [PATCH 2/2] Created prime.js --- src/algorithms/math/prime.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/algorithms/math/prime.js 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.`); +}