JavaScript Snippet

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

Difficulty: Medium

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.

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 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.