Math

Huy Do
2 min readDec 6, 2020

Factorial

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example

5! = 5 * 4 * 3 * 2 * 1 = 120

We can use for loop:

/** 
* @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;
}

We can use recursive

/** 
* @param {number} number
* @return {number}
*/export default
function factorialRecursive(number) {
return number > 1 ? number * factorialRecursive(number - 1) : 1;
}

Fibonacci Number

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...

/** 
* 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;
}

Primality Test

A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 6 is composite because it is the product of two numbers (2 × 3) that are both smaller than 6.

/** * @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;
}

References:

https://github.com/trekhleb/javascript-algorithms

--

--

Huy Do
0 Followers

Full Stack SE. I love to build beautiful web apps and learn new technologies.