Leetcode/Guide/Math
Last edited by dave on 08/11/2025, 16:23:16 UTC
Contents
This guide summarizes essential math operations, utility functions, and coding test–friendly techniques in JavaScript.
Everything is pure function–based, no classes, and uses clear, descriptive variable names for readability and reusability.
🧮 Core Math Concepts
JavaScript’s Math object gives you most math tools you’ll need.
Always remember:
- Numbers are 64-bit floating point (no integer type).
- Avoid direct floating comparisons — use a tolerance (
Math.abs(a - b) < 1e-9). - Common constants:
Math.PI,Math.E,Math.SQRT2,Math.LN2,Math.LOG10E
1️⃣ Basic Operations & Safe Utilities
function clampValue(value, minValue, maxValue) { return Math.min(Math.max(value, minValue), maxValue); } function roundToDecimalPlaces(value, decimalPlaces) { const power = Math.pow(10, decimalPlaces); return Math.round(value * power) / power; } function isApproximatelyEqual(a, b, tolerance = 1e-9) { return Math.abs(a - b) < tolerance; } function randomIntegerInRange(minValue, maxValue) { return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue; } function randomFloatInRange(minValue, maxValue) { return Math.random() * (maxValue - minValue) + minValue; }
✅ Usage
console.log(clampValue(15, 0, 10)); // 10 console.log(roundToDecimalPlaces(3.14159, 2)); // 3.14 console.log(isApproximatelyEqual(0.1 + 0.2, 0.3)); // true
2️⃣ Factorial, GCD, and LCM
function factorialUsingLoop(number) { if (number < 0) return NaN; let result = 1; for (let i = 2; i <= number; i++) { result *= i; } return result; } function greatestCommonDivisor(a, b) { while (b !== 0) { const temp = b; b = a % b; a = temp; } return a; } function leastCommonMultiple(a, b) { return Math.abs(a * b) / greatestCommonDivisor(a, b); }
✅ Usage
console.log(factorialUsingLoop(5)); // 120 console.log(greatestCommonDivisor(36, 48)); // 12 console.log(leastCommonMultiple(4, 6)); // 12
3️⃣ Prime Numbers and Sieve
function isPrime(number) { if (number < 2) return false; for (let divisor = 2; divisor * divisor <= number; divisor++) { if (number % divisor === 0) return false; } return true; } function generatePrimesUpTo(limit) { const isPrimeArray = new Array(limit + 1).fill(true); isPrimeArray[0] = isPrimeArray[1] = false; for (let num = 2; num * num <= limit; num++) { if (isPrimeArray[num]) { for (let multiple = num * num; multiple <= limit; multiple += num) { isPrimeArray[multiple] = false; } } } return isPrimeArray .map((isPrime, index) => (isPrime ? index : null)) .filter((num) => num !== null); }
✅ Usage
console.log(isPrime(17)); // true console.log(generatePrimesUpTo(20)); // [2, 3, 5, 7, 11, 13, 17, 19]
4️⃣ Power, Exponent, and Logarithm Tricks
function computePower(base, exponent) { return Math.pow(base, exponent); } function computeSquareRoot(number) { return Math.sqrt(number); } function computeLogBase(value, base) { return Math.log(value) / Math.log(base); }
✅ Usage
console.log(computePower(2, 10)); // 1024 console.log(computeSquareRoot(16)); // 4 console.log(computeLogBase(8, 2)); // 3
5️⃣ Average, Median, and Mode
function calculateAverage(numbers) { const sum = numbers.reduce((acc, n) => acc + n, 0); return sum / numbers.length; } function calculateMedian(numbers) { const sorted = [...numbers].sort((a, b) => a - b); const middle = Math.floor(sorted.length / 2); return sorted.length % 2 !== 0 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2; } function calculateMode(numbers) { const frequencyMap = Object.create(null); for (const num of numbers) { frequencyMap[num] = (frequencyMap[num] || 0) + 1; } const maxFreq = Math.max(...Object.values(frequencyMap)); return Object.keys(frequencyMap) .filter((key) => frequencyMap[key] === maxFreq) .map(Number); }
✅ Usage
console.log(calculateAverage([1, 2, 3, 4, 5])); // 3 console.log(calculateMedian([7, 2, 5, 10, 8])); // 7 console.log(calculateMode([1, 1, 2, 2, 3])); // [1, 2]
6️⃣ Coordinate Geometry Helpers
function calculateDistanceBetweenPoints(x1, y1, x2, y2) { const dx = x2 - x1; const dy = y2 - y1; return Math.sqrt(dx * dx + dy * dy); } function calculateMidpoint(x1, y1, x2, y2) { return { x: (x1 + x2) / 2, y: (y1 + y2) / 2 }; } function calculateLineSlope(x1, y1, x2, y2) { if (x1 === x2) return Infinity; return (y2 - y1) / (x2 - x1); }
✅ Usage
console.log(calculateDistanceBetweenPoints(0, 0, 3, 4)); // 5 console.log(calculateMidpoint(0, 0, 4, 4)); // {x:2, y:2} console.log(calculateLineSlope(0, 0, 2, 4)); // 2
7️⃣ Math Patterns for Coding Tests
Sum of Digits
function sumOfDigits(number) { let sum = 0; while (number > 0) { sum += number % 10; number = Math.floor(number / 10); } return sum; }
Reverse Number
function reverseInteger(number) { let reversed = 0; const sign = number < 0 ? -1 : 1; number = Math.abs(number); while (number > 0) { reversed = reversed * 10 + (number % 10); number = Math.floor(number / 10); } return sign * reversed; }
Check Power of Two
function isPowerOfTwo(number) { return number > 0 && (number & (number - 1)) === 0; }
✅ Usage
console.log(sumOfDigits(1234)); // 10 console.log(reverseInteger(-123)); // -321 console.log(isPowerOfTwo(16)); // true
8️⃣ Random & Probability Utilities
function simulateCoinFlip() { return Math.random() < 0.5 ? "Heads" : "Tails"; } function shuffleArray(inputArray) { for (let i = inputArray.length - 1; i > 0; i--) { const randomIndex = Math.floor(Math.random() * (i + 1)); [inputArray[i], inputArray[randomIndex]] = [inputArray[randomIndex], inputArray[i]]; } return inputArray; } function weightedRandomChoice(weights) { const totalWeight = weights.reduce((a, b) => a + b, 0); const randomValue = Math.random() * totalWeight; let runningSum = 0; for (let i = 0; i < weights.length; i++) { runningSum += weights[i]; if (randomValue < runningSum) return i; } }
✅ Usage
console.log(simulateCoinFlip()); console.log(shuffleArray([1, 2, 3, 4, 5])); console.log(weightedRandomChoice([0.1, 0.3, 0.6])); // likely returns 2
9️⃣ Geometry & Trigonometry Essentials
function degreesToRadians(degrees) { return degrees * (Math.PI / 180); } function radiansToDegrees(radians) { return radians * (180 / Math.PI); } function calculateCircleArea(radius) { return Math.PI * radius * radius; } function calculateTriangleArea(base, height) { return 0.5 * base * height; }
✅ Usage
console.log(degreesToRadians(180)); // 3.14159... console.log(calculateCircleArea(5)); // 78.5398...
🔟 Useful Math Patterns in Interviews
| Pattern | Key Formula | Example |
|---|---|---|
| Sum of 1..n | n × (n+1)/2 | 1 + 2 + ... + 100 |
| Sum of Squares | n(n+1)(2n+1)/6 | 1² + 2² + ... |
| Euclidean Distance | √((x₂−x₁)² + (y₂−y₁)²) | Geometry |
| Compound Interest | A = P(1 + r/n)^(n×t) | Finance problems |
| Fibonacci | f(n)=f(n-1)+f(n-2) | Recursive/iterative DP |
| Power of Two | (n & (n−1)) == 0 | Bitwise trick |
| Swap (No Temp) | a ^= b; b ^= a; a ^= b; | Bitwise |
🚀 Key Takeaways
- Know your
Mathmethods:Math.floor,Math.ceil,Math.abs,Math.round,Math.max,Math.min,Math.random,Math.sqrt,Math.pow. - Prefer
Number.isFinite()/Number.isInteger()for numeric checks. - Always watch floating-point precision.
- Use loops and descriptive variable names for clarity in coding interviews.
- Master patterns: GCD/LCM, prime, digit math, geometry, probability.
With these utilities and patterns, you can handle almost any math-related JavaScript coding test efficiently and clearly.
Backlinks (1)
- General
No backlinks yet.
- User
- Redirects
No backlinks yet.
- Media
No backlinks yet.
- Categories
No backlinks yet.
Categories (0)
No categories assigned to this page.
Edit Level
> Signed In Users
Latest on Lounge
Join the conversation about the 'Leetcode/Guide/Math' article →
No comments yet. Be the first to comment!