CATEGORY 3 OF 13

Number & Math

Master the numeric operations that underpin countless coding problems: digit extraction, modular arithmetic, integer manipulation, and mathematical formulas.

Time: O(n) or O(d)
Space: O(1)

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

  1. Watch for overflow — multiplying or adding large numbers can exceed integer bounds. Use long in Java, or check bounds before operations
  2. Handle negative numbers explicitly — digit extraction, modulo, and division all behave differently with negatives depending on the language
  3. Zero is special — it's neither positive nor negative, it's a palindrome, and dividing by zero crashes
  4. Use integer math when possible — avoid floating-point for problems that only need integers; floats introduce precision errors

Common Mistakes

  1. Integer overflow: Multiplying two large ints silently wraps in Java/Go. Always consider if intermediate results could overflow
  2. Negative modulo: -7 % 3 is -1 in Java/Go but 2 in Python. Normalize with ((x % n) + n) % n
  3. Off-by-one in prime check: Check divisors up to and including sqrt(n), not just less than
  4. Forgetting zero edge case: Is 0 a palindrome? (yes) Is 0 prime? (no) Is 0 a power of two? (no)
  5. Using floating-point equality: Never compare floats with ==. Use a tolerance or stick to integers

When to Use

Reverse a number or check if it's a palindrome
Extract or sum individual digits
Check divisibility or find factors
Convert between number bases
Implement FizzBuzz or similar modulo logic
Calculate GCD, LCM, or factorial
Check if a number is prime or power of two
Roman numeral conversions

Template

1# --- Digit Extraction Loop ---
2def process_digits(n):
3 n = abs(n)
4 while n > 0:
5 digit = n % 10 # get last digit
6 n //= 10 # remove last digit
7 # process digit
8
9# --- Divisibility Check ---
10def is_divisible(n, d):
11 return n % d == 0
12
13# --- Sum Formula (1 to n) ---
14def sum_1_to_n(n):
15 return n * (n + 1) // 2
16
17# --- Euclidean GCD ---
18def gcd(a, b):
19 while b:
20 a, b = b, a % b
21 return a
{ }

Syntax Reference

1# === Basic Operations ===
2x // y # integer division (floor)
3x % y # modulo (always non-negative if y > 0)
4abs(x) # absolute value
5pow(x, y) # x^y (or x ** y)
6divmod(x, y) # returns (quotient, remainder)
7
8# === Digit Extraction ===
9last_digit = n % 10 # last digit
10n = n // 10 # remove last digit
11digits = [int(d) for d in str(n)] # all digits
12
13# === Math Module ===
14import math
15math.sqrt(x) # square root (float)
16math.isqrt(x) # integer square root
17math.gcd(a, b) # greatest common divisor
18math.lcm(a, b) # least common multiple (3.9+)
19math.factorial(n) # n!
20math.floor(x) # floor
21math.ceil(x) # ceiling
22math.log2(x) # log base 2
23math.inf # positive infinity
24
25# === Conversion ===
26int("42") # string to int
27str(42) # int to string
28bin(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):
3 sign = -1 if n < 0 else 1
4 n = abs(n)
5 result = 0
6 while n > 0:
7 result = result * 10 + n % 10
8 n //= 10
9 return sign * result
10
11# --- Check Palindrome Number ---
12def is_palindrome(n):
13 if n < 0: return False
14 return str(n) == str(n)[::-1]
15
16# --- Sum of Digits ---
17def sum_digits(n):
18 n = abs(n)
19 total = 0
20 while n > 0:
21 total += n % 10
22 n //= 10
23 return total
24
25# --- GCD and LCM ---
26def gcd(a, b):
27 while b: a, b = b, a % b
28 return a
29def lcm(a, b):
30 return a * b // gcd(a, b)
31
32# --- Is Prime ---
33def is_prime(n):
34 if n < 2: return False
35 for i in range(2, int(n**0.5) + 1):
36 if n % i == 0: return False
37 return True
O(n)

Complexity

OperationTimeNotes
Digit extraction (all)O(d)d = number of digits
Reverse integerO(d)Process each digit once
GCD (Euclidean)O(log min(a,b))Very efficient
Primality checkO(sqrt(n))Check divisors up to sqrt
FactorialO(n)Multiply 1 through n
Power (exponentiation)O(log y)Using fast exponentiation
Base conversionO(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