Skip to content

Created math algorithms fibonacci.js and prime.js #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/algorithms/math/fibonacci.js
Original file line number Diff line number Diff line change
@@ -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);
25 changes: 25 additions & 0 deletions src/algorithms/math/prime.js
Original file line number Diff line number Diff line change
@@ -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.`);
}