Number & Math
Master the numeric operations that underpin countless coding problems: digit extraction, modular arithmetic, integer manipulation, and mathematical formulas.
Learn & Reference
Understanding the Pattern
Number & Math
Numbers are deceptively tricky. Problems involving integers, digits, and mathematical operations appear simple but are full of edge cases — overflow, negative numbers, zero, and off-by-one errors. Building fluency with numeric operations makes you faster on problems that combine math with other patterns.
Core Operations
Digit Extraction
Pull individual digits from a number using modulo (% 10) and integer division (// 10 or / 10). This is the foundation for reversing numbers, checking palindromes, and summing digits.
Modular Arithmetic
The modulo operator (%) gives the remainder after division. It's essential for:
- Cycling through ranges (clock arithmetic)
- Checking divisibility
- Wrapping around boundaries
Integer Division
Dividing integers truncates toward zero in most languages. Be careful with negative numbers — Python's // floors toward negative infinity, while Java/Go truncate toward zero.
Mathematical Formulas
Know the common formulas: sum of 1..n = n*(n+1)/2, GCD via Euclidean algorithm, prime checking up to sqrt(n).
Key Principles
- Watch for overflow — multiplying or adding large numbers can exceed integer bounds. Use
longin Java, or check bounds before operations - Handle negative numbers explicitly — digit extraction, modulo, and division all behave differently with negatives depending on the language
- Zero is special — it's neither positive nor negative, it's a palindrome, and dividing by zero crashes
- Use integer math when possible — avoid floating-point for problems that only need integers; floats introduce precision errors
Common Mistakes
- Integer overflow: Multiplying two large ints silently wraps in Java/Go. Always consider if intermediate results could overflow
- Negative modulo:
-7 % 3is-1in Java/Go but2in Python. Normalize with((x % n) + n) % n - Off-by-one in prime check: Check divisors up to and including
sqrt(n), not just less than - Forgetting zero edge case: Is 0 a palindrome? (yes) Is 0 prime? (no) Is 0 a power of two? (no)
- Using floating-point equality: Never compare floats with
==. Use a tolerance or stick to integers
When to Use
Template
1# --- Digit Extraction Loop ---2def process_digits(n):3n = abs(n)4while n > 0:5digit = n % 10 # get last digit6n //= 10 # remove last digit7# process digit89# --- Divisibility Check ---10def is_divisible(n, d):11return n % d == 01213# --- Sum Formula (1 to n) ---14def sum_1_to_n(n):15return n * (n + 1) // 21617# --- Euclidean GCD ---18def gcd(a, b):19while b:20a, b = b, a % b21return a
Syntax Reference
1# === Basic Operations ===2x // y # integer division (floor)3x % y # modulo (always non-negative if y > 0)4abs(x) # absolute value5pow(x, y) # x^y (or x ** y)6divmod(x, y) # returns (quotient, remainder)78# === Digit Extraction ===9last_digit = n % 10 # last digit10n = n // 10 # remove last digit11digits = [int(d) for d in str(n)] # all digits1213# === Math Module ===14import math15math.sqrt(x) # square root (float)16math.isqrt(x) # integer square root17math.gcd(a, b) # greatest common divisor18math.lcm(a, b) # least common multiple (3.9+)19math.factorial(n) # n!20math.floor(x) # floor21math.ceil(x) # ceiling22math.log2(x) # log base 223math.inf # positive infinity2425# === Conversion ===26int("42") # string to int27str(42) # int to string28bin(42) # "0b101010"29oct(42) # "0o52"30hex(42) # "0x2a"31int("101010", 2) # binary string to int
Common Recipes
1# --- Reverse an Integer ---2def reverse_integer(n):3sign = -1 if n < 0 else 14n = abs(n)5result = 06while n > 0:7result = result * 10 + n % 108n //= 109return sign * result1011# --- Check Palindrome Number ---12def is_palindrome(n):13if n < 0: return False14return str(n) == str(n)[::-1]1516# --- Sum of Digits ---17def sum_digits(n):18n = abs(n)19total = 020while n > 0:21total += n % 1022n //= 1023return total2425# --- GCD and LCM ---26def gcd(a, b):27while b: a, b = b, a % b28return a29def lcm(a, b):30return a * b // gcd(a, b)3132# --- Is Prime ---33def is_prime(n):34if n < 2: return False35for i in range(2, int(n**0.5) + 1):36if n % i == 0: return False37return True
Complexity
| Operation | Time | Notes |
|---|---|---|
| Digit extraction (all) | O(d) | d = number of digits |
| Reverse integer | O(d) | Process each digit once |
| GCD (Euclidean) | O(log min(a,b)) | Very efficient |
| Primality check | O(sqrt(n)) | Check divisors up to sqrt |
| Factorial | O(n) | Multiply 1 through n |
| Power (exponentiation) | O(log y) | Using fast exponentiation |
| Base conversion | O(d) | d = digits in result |
Watch Out
- ✗Integer overflow: Multiplying two large ints silently wraps in Java/Go. Always consider if intermediate results could overflow
- ✗Negative modulo: `-7 % 3` is `-1` in Java/Go but `2` in Python. Normalize with `((x % n) + n) % n`
- ✗Off-by-one in prime check: Check divisors up to and including `sqrt(n)`, not just less than
- ✗Forgetting zero edge case: Is 0 a palindrome? (yes) Is 0 prime? (no) Is 0 a power of two? (no)
- ✗Using floating-point equality: Never compare floats with `==`. Use a tolerance or stick to integers