Math

5! = 5 * 4 * 3 * 2 * 1 = 120
/** 
* @param {number} number
* @return {number}
*/
export default function factorial(number) {
let result = 1;
for (let i = 2; i <= number; i += 1) {
result *= i;
}
return result;
}
/** 
* @param {number} number
* @return {number}
*/export default
function factorialRecursive(number) {
return number > 1 ? number * factorialRecursive(number - 1) : 1;
}
/** 
* Return a fibonacci sequence as an array. *
* @param n * @return {number[]}
*/export default
function fibonacci(n) {
const fibSequence = [1];
let currentValue = 1;
let previousValue = 0;
if (n === 1) {
return fibSequence;
}
let iterationsCounter = n - 1;
while (iterationsCounter) {
currentValue += previousValue;
previousValue = currentValue - previousValue;
fibSequence.push(currentValue);
iterationsCounter -= 1;
}
return fibSequence;
}
/** * @param {number} number 
* @return {boolean}
*/export default
function trialDivision(number) {
// Check if number is integer.
if (number % 1 !== 0) {
return false; }
if (number <= 1) { // If number is less than one then it isn't prime by definition.
return false; }
if (number <= 3) { // All numbers from 2 to 3 are prime.
return true; }
// If the number is not divided by 2 then we may eliminate all //further even dividers.
if (number % 2 === 0) {
return false; }
// If there is no dividers up to square root of n then there is no //higher dividers as well.

const dividerLimit = Math.sqrt(number);
for (let divider = 3; divider <= dividerLimit; divider += 2) {
if (number % divider === 0) {
return false; }
}
return true;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store