Code Snippets
/

Number Tricks: Integer Check, Digit Length, Exponent, GCD, Primes, Random Hex

Number Tricks: Integer Check, Digit Length, Exponent, GCD, Primes, Random Hex

A collection of small number-theory and number-formatting recipes that show up constantly: inspecting a number (integer check, digit length), looped algorithms (binary exponent, Euclidean GCD, prime listing), digit-level transforms (sort, reverse, sum), and a couple of random helpers (hex color, plus pointers to the existing range and shuffle entries). Each accordion is its own tight group so you can pull just the recipe you need.

JavaScript
Medium
4 snippets
math
number-theory
loops
gcd-lcm

781 views

20

// Number.isInteger is strict: rejects strings, NaN, Infinity, floats.
console.log(Number.isInteger(42));       // true
console.log(Number.isInteger(42.0));     // true (still an integer value)
console.log(Number.isInteger(42.5));     // false
console.log(Number.isInteger('42'));     // false (string)
console.log(Number.isInteger(NaN));      // false
console.log(Number.isInteger(Infinity)); // false

// Compare with the looser isFinite + Math.trunc check:
const isWholeNumber = (x) => Number.isFinite(x) && Math.trunc(x) === x;
console.log(isWholeNumber(42.0)); // true
console.log(isWholeNumber(42.5)); // false

// Digit length: math version (no string coercion).
const digitLengthMath = (n) => {
    if (n === 0) return 1;
    return Math.floor(Math.log10(Math.abs(n))) + 1;
};

console.log(digitLengthMath(0));     // 1
console.log(digitLengthMath(7));     // 1
console.log(digitLengthMath(12345)); // 5
console.log(digitLengthMath(-9999)); // 4 (sign ignored)

// Digit length: string version (handles edge cases more naturally).
const digitLengthString = (n) => Math.abs(Math.trunc(n)).toString().length;
console.log(digitLengthString(12345)); // 5
console.log(digitLengthString(-9999)); // 4

Number.isInteger is the modern, type-aware integer check; it rejects strings even if they look like numbers, which is usually the safe behavior. The looser isWholeNumber helper is for when you have already accepted a number-or-numeric-string input and just want "no fractional part". For digit length, the math form (floor(log10(abs(n))) + 1) is fast and avoids allocating a string, but it has a degenerate case at zero (the formula yields -Infinity), so guard with an explicit zero check. The string form (.toString().length) is shorter and gets the zero case for free; use it unless you are in a hot loop.