001 Notes

Mathematical Numeric Reasoning Professional Playbook

Overview and Reading Path

Mathematical numeric reasoning solves problems by converting the statement into number properties, formulas, or compact arithmetic invariants.

Use this family when the problem asks about:

  • remainders
  • divisibility
  • GCD / LCM
  • primes
  • combinations or permutations
  • powers
  • digits and bases
  • coordinates and geometry

Read in this order:

  1. Identify the numeric object.
  2. Identify the invariant or formula.
  3. Choose representation and bounds.
  4. Handle edge cases: zero, one, negative values, overflow, and modulo.
  5. Prove the formula on a small example.

Core Vocabulary

TermMeaning
InvariantNumeric property preserved by each step
ModulusNumber used to reduce values into remainder classes
DivisorNumber that evenly divides another
GCDGreatest common divisor
PrimeNumber greater than 1 with no positive divisors except 1 and itself
CombinationChoice count where order does not matter
PermutationArrangement count where order matters
Place valueContribution of a digit based on its position
Cross productInteger geometry test for orientation or area

Beginner Mental Model

Think of turning a word problem into a rule about numbers.

The brute-force way lists possibilities. Numeric reasoning asks:

Can a property, formula, or invariant answer this directly?

Examples:

same remainder -> divisible difference
gcd -> shared divisibility
factorization -> prime building blocks
combinatorics -> count without listing
place value -> parse digits
cross product -> compare geometry without floats

From Brute Force To This Pattern

Brute force enumerates values or simulations:

try every divisor
list every arrangement
multiply one step at a time
compare geometry with floating-point slopes
parse digits without bounds

Mathematical reasoning changes the question:

What property stays true if I reduce the numbers?

The shift is from enumeration to invariant-preserving transformation.

What Information Becomes Reusable

Reusable information is numeric structure:

  • remainder classes
  • prime factors
  • gcd relationships
  • factorials and inverse factorials
  • exponent bits
  • digit place values
  • reduced slopes
  • squared distances

What This Mental Model Prevents

This model prevents:

  • enumerating combinations that a formula can count
  • overflowing before applying modulo
  • comparing floating-point slopes
  • recomputing primality for every number
  • ignoring zero, one, negative, or duplicate edge cases
  • using a formula without proving it counts each object once

Small Visual Model

large value:
    10^18 + 7

modular reasoning:
    only value % m matters

factor reasoning:
    only prime building blocks matter

geometry reasoning:
    only reduced slope or cross product matters

Core Mental Model

The central question is:

What numeric property can replace brute-force enumeration?

Mathematical reasoning problems become simple when the original objects can be replaced by a property that is smaller, exact, and preserved by the operations in the statement.

Most numeric solutions are built from four contracts:

property:
    divisibility, remainder, count formula, factor, place value, orientation

safe reduction:
    modulo, gcd, factorization, exponent halving, digit transition

representation:
    integer width, normalized pair, canonical sign, rank, mask, or formula state

edge discipline:
    handle zero, bounds, overflow, signs, duplicates, and precision

How To Read This Family Visually

Use the same symbols throughout this section:

[]    active value, digit, factor, point, or formula term
{}    canonical property: remainder, gcd, factor set, count, slope, carry
^     current value, bit, digit, divisor, or coordinate
-->   reduction, normalization, recurrence, or formula step
x     impossible case, duplicate case, overflow-prone form, or invalid value
==    property-equivalent values
...   values not enumerated because the property replaces them

One-minute mental model:

see many numeric cases
    -> ask what property preserves the answer
    -> store a canonical representation of that property
    -> reduce each raw value into that representation
    -> invariant: reduced properties answer the original numeric question

Read every diagram as:

shape:
    what raw numeric objects are present?
memory:
    what property replaces brute force?
action:
    what reduction or formula step happens?
invariant:
    why does the reduced property preserve the answer?

ASCII Visual Map

Numeric reasoning should feel like replacing many raw cases with a smaller canonical property that preserves the answer.

modulo classes:

values by remainder mod 5:

class 0:  0   5   10   15
class 1:  1   6   11   16
class 2:  2   7   12   17
class 3:  3   8   13   18
class 4:  4   9   14   19

Equal prefix remainders imply the subarray difference is divisible by 5.
Euclid reduction:

gcd(48, 18)
    48 = 2 * 18 + 12
    18 = 1 * 12 + 6
    12 = 2 * 6  + 0

gcd is 6 because common divisors survive each remainder step.
normalized slope:

point A (x1, y1) ---- point B (x2, y2)

dy = y2 - y1
dx = x2 - x1
g  = gcd(abs(dy), abs(dx))

key = (dy / g, dx / g) with one fixed sign convention

No floating-point slope is needed.
fast exponentiation:

x^13

13 in binary = 1101

bit:      8     4     2     1
power:  x^8   x^4   x^2    x
use:     yes   yes   no    yes

answer = x^8 * x^4 * x
digit carry:

      9  9  8
  +      7  6
  -------------
      ?  ?  ?

process from right:
    digit_sum = a[i] + b[j] + carry
    output digit_sum % 10
    carry = digit_sum / 10

Numeric Property

First name the property that matters more than the raw value.

Problem shapeProperty
subarrays divisible by kequal prefix remainders
common divisibilitygcd or prime factors
primality repeated over rangesieve marking
combinations/permutationscount formula with constraints
large powerexponent bits and modular multiplication
digit processingplace value and carry
geometryslope, distance squared, orientation, area

Problem Shape Diagrams

subarrays divisible by k:

prefix sums:       0   4   9   14   17
remainder mod 5:   0   4   4    4    2
                       ^        ^

Equal remainders mean the subarray between them sums to a multiple of k.
invariant: equal remainder classes preserve divisibility of differences
common divisibility:

24 factors: 2 * 2 * 2 * 3
18 factors: 2 * 3 * 3

common part: 2 * 3 = 6

gcd stores the shared divisibility structure.
invariant: gcd preserves exactly the common factors needed by the answer
primality repeated over range:

numbers: 2 3 4 5 6 7 8 9 10
mark 2:  P P x P x P x P  x
mark 3:  P P x P x P x x  x

Sieve marks composites once small primes explain them.
invariant: unmarked numbers after small-prime marking are prime candidates
combinations / permutations:

choose 3 of 5:

items:  A B C D E
slots:  _ _ _

Formula counts equivalent choices without listing every subset.
invariant: each valid choice is counted once by the formula
large power:

x^13 = x^(8 + 4 + 1)

binary exponent bits:
8  4  2  1
1  1  0  1

Multiply only selected squared powers.
invariant: selected bits multiply to the original exponent value
digit processing:

number string:  "507"

value scan:
0 --'5'--> 5 --'0'--> 50 --'7'--> 507

Each digit shifts previous value by base 10.
invariant: processed prefix has the numeric value represented so far
geometry:

A(x1,y1) -------- B(x2,y2)
     \              /
      \            /
       C(x3,y3)

Use integer relations:
    slope key
    distance squared
    cross product orientation
invariant: integer formulas preserve geometric equality/orientation exactly

If raw values are only needed through a property, carry the property. If raw values are needed for ordering or adjacency, another family may be primary.

Safe Reduction

A reduction is safe when it preserves the answer.

a and b have same remainder mod k:
    their difference is divisible by k

gcd(a, b):
    preserves exactly the common divisors of a and b

normalized slope (dy/g, dx/g):
    preserves line direction without floating-point precision

fast power:
    x^n = (x^2)^(n/2) when n is even

Do not reduce away information that the answer still needs. Modulo preserves remainders, not magnitude. Compression preserves order, not distance.

Representation

Numeric code is often wrong because the representation is not canonical.

PropertyRobust representation
remaindernormalized value in [0, k)
fraction/slopedivide by gcd and fix sign convention
point distancesquared integer distance
factor setprime factors or exponent map
digit statecarry, index, tight flag, or current value
combinatoric countfactorials/inverses or recurrence table
geometry orientationcross product sign

Use integer formulas when possible. Floating point should be avoided for slopes, collinearity, and equality unless the problem explicitly works in continuous precision.

Edge Discipline

Handle numeric edge cases before the main loop.

zero:
    gcd, division, slope, and modulo need explicit behavior

negative values:
    normalize remainder and sign

overflow:
    promote before multiplication or use modular multiplication

duplicates:
    count separately when normalized keys collapse

precision:
    prefer cross products, squared distances, or rational keys

Many numeric solutions are short because the core identity is short. The edge discipline is where most real correctness work lives.

Invariant-Preserving Transformation

The transformation must preserve exactly what the answer asks.

StrategyPreserved invariant
modular arithmeticequality of relevant remainders
GCD/LCMcommon divisors and multiples
sieve/factorizationprimality/factor membership
combinatoricscount of equivalent choices
fast exponentiationvalue of the represented power
digit/base mathnumeric value of processed prefix plus carry
geometrygeometric relation under integer formula

State the invariant before coding. If the invariant is vague, the formula is probably being applied by memory rather than by proof.

Universal Numeric Template

identify the numeric property that controls the answer
choose a canonical representation for that property
handle zero, sign, bounds, overflow, duplicates, and precision

for each value, digit, factor, point, or formula step:
    reduce to the canonical property
    update counts, factors, recurrence, or result
    preserve the stated invariant

return the exact count, decision, value, or normalized result

Strategy-Specific Mental Model

StrategyMental modelMain risk
modular arithmeticremainder classes replace raw sumsnegative modulo
GCD/LCMrepeated Euclid preserves common divisorsdivision by zero/overflow
sieve/factorizationsmall primes explain many valueswrong marking bounds
combinatoricsformula counts equivalent casesovercounting duplicates
fast exponentiationexponent bits select squared powersoverflow before modulo
digit mathprocess place values with carry/stateleading zeros or bounds
geometryinteger formulas replace drawingsfloat slope precision

Mini Translation Table

Statement signalLikely numeric model
”divisible by k”prefix remainder classes
”common factor”gcd or prime factorization
”count primes”sieve
”large exponent”fast power with modulo
”number of ways” with direct formulacombinatorics
”add/multiply represented as string”digit math and carry
”points on line/square/area”normalized geometry key

Mini Traces

Trace 1: subarrays divisible by k.

k = 5
prefix sums:       0   4   9   14
remainders:        0   4   4    4
                       ^        ^

step:
    current remainder 4 has appeared before
    add previous count of remainder 4

invariant:
    equal remainders define subarrays whose sum is divisible by k

Trace 2: normalized slope.

points:
A(1,1), B(3,3)

dy = 2
dx = 2
g = 2
key = (1, 1)

invariant:
    all points on the same direction from A share the same normalized key

Contrast Diagrams

GCD/factorization vs graph connectivity from factors:

numeric primary:
    gcd(a, b) answers divisibility directly
    invariant: gcd preserves common divisors

connectivity primary:
    number -> prime factor -> other number
    invariant: shared factor creates an edge/component relation

Modulo counting vs sliding window:

modulo counting:
    prefix remainder repeats can be far apart
    invariant: equal remainders imply divisible difference

sliding window:
    left/right maintain one active contiguous region
    invariant: current window is valid after repair

Misclassification Checks

Use this family when arithmetic structure is the reason the problem becomes simple. Be careful when:

SymptomBetter family may be
values are arbitrary states with choicesState Space Exploration
sorted feasibility drives the answerOrdered Optimization
range updates or queries dominateRange Query & Indexed Aggregation
graph edges are built from factorsConnectivity Discovery may be primary
a one-pass count is enoughSequential Aggregation

The clean test is: can you replace brute force with a named numeric property and prove the replacement preserves the answer?

What This Family Is / Is Not

Use this family when arithmetic structure is the reason the problem becomes simple.

Do not use it when:

  • the formula is only a small helper inside a larger graph/search problem
  • values must be explored as arbitrary states
  • ordering or range updates are the main challenge
  • a direct scan with counts is enough

Universal Template

identify numeric property
choose safe representation
handle edge cases and bounds
apply invariant-preserving transformation
compute formula or reduced state
return exact numeric answer

Detailed Translation Workflow

Translate every numeric problem in this order:

1. What numeric property is being tested or counted?
2. Can values be reduced by modulo, gcd, factors, exponent bits, or geometry formulas?
3. What representation avoids overflow or precision loss?
4. What are the edge cases: zero, one, negative, duplicate, empty, huge?
5. Does the formula count each valid object exactly once?
6. What complexity improvement does the property provide over enumeration?

If the property does not reduce work or improve correctness, it is probably just a helper, not the main pattern.

Strategy Map

StrategyUse whenInvariant
Modular arithmeticremainders decide equality or cyclesvalues can be reduced modulo m
GCD / LCMdivisibility and common factors mattergcd preserves common divisors
Prime sieve / factorizationprimality or factors repeatmark or divide by small primes
Combinatoricscount without enumeratingformula counts equivalent choices
Fast exponentiationlarge powersexponent bits select squared powers
Digit math / base conversionplace value mattersprocessed prefix has known numeric value
Geometrycoordinates encode shapeformulas preserve geometric relation

Problem Translation Table

Problem typeNumeric stateKey ruleEngine
Subarray Sums Divisible by Kprefix remainder countsequal remainders form divisible rangemodular arithmetic
Pow(x, n)base, exponentsquare base, halve exponentfast exponentiation
Count Primesmarked composite arraysieve multiplesprime sieve
Ugly Numberrepeated factor divisionremove allowed factorsdivisibility
Greatest Common Divisor Traversalgcd of valuesshared factor connects valuesgcd/factorization
LCM of Arrayrunning lcmlcm(a,b)=a/gcd(a,b)*bGCD/LCM
Unique Paths Formulam+n-2 choose m-1choose down positionscombinatorics
Pascal Triangleprevious rowadjacent sumscombinatorics
Combination Sum Count Formulacountsmultiply/divide safelycombinatorics
Super Powexponent digitsmodular exponent compositionmodular exponentiation
Add Binarycarry and indexbase-2 place valuedigit math
String to Integersign, valueclamp on overflowdigit parsing
Plus Onecarry from rightbase-10 carrydigit math
Happy Numberdigit-square sumcycle detection over numeric statedigit math
Max Points on a Linereduced slopenormalize by gcdgeometry
Valid Squarepairwise distancesequal sides and diagonalsgeometry
Rectangle Overlapcoordinate boundsprojections overlapgeometry

Canonical Examples

Modular Arithmetic: Subarrays Divisible by K

Invariant:

Two prefixes with the same remainder differ by a sum divisible by k.
from collections import defaultdict


def subarrays_div_by_k(nums, k):
    counts = defaultdict(int)
    counts[0] = 1
    prefix = 0
    ans = 0

    for value in nums:
        prefix = (prefix + value) % k
        ans += counts[prefix]
        counts[prefix] += 1

    return ans

GCD: Euclid

Invariant:

gcd(a, b) == gcd(b, a % b)
def gcd(a, b):
    while b:
        a, b = b, a % b
    return abs(a)

Sieve: Count Primes

Invariant:

When p is prime, every unmarked multiple of p beyond p*p is composite.
def count_primes(n):
    if n <= 2:
        return 0
    prime = [True] * n
    prime[0] = prime[1] = False
    p = 2
    while p * p < n:
        if prime[p]:
            for multiple in range(p * p, n, p):
                prime[multiple] = False
        p += 1
    return sum(prime)

Fast Exponentiation

Invariant:

answer * base^exp remains equal to the original target power.
def fast_pow(x, n):
    if n < 0:
        x = 1 / x
        n = -n

    ans = 1
    while n:
        if n & 1:
            ans *= x
        x *= x
        n >>= 1
    return ans

Geometry: Max Points Slope Key

Invariant:

All points on the same line through an anchor share the same normalized slope.

Normalize slope by dividing (dy, dx) by gcd(abs(dy), abs(dx)), and choose a consistent sign convention.

Decision Rules

Use modular arithmetic when only remainders matter. Use GCD when divisibility or shared factors are the core relation. Use a sieve when many primality checks are needed over a bounded range. Use combinatorics when order/choice counts can be calculated directly. Use fast exponentiation for large exponents or repeated modular powers. Use digit math when processing place values, carries, or base conversion. Use geometry formulas when coordinates encode orientation, distance, area, or overlap.

Common Failure Modes

  • Forgetting that modulo behavior with negatives differs across languages.
  • Overflowing before applying modulo.
  • Computing LCM as a * b / gcd without reducing first.
  • Starting sieve marking at 2 * p instead of p * p.
  • Counting permutations when the formula needs combinations.
  • Mishandling exponent 0 or negative exponents.
  • Losing carry in digit problems.
  • Comparing floating-point slopes instead of normalized integer pairs.

Performance Notes

Modulo, GCD, and digit scans are usually cheap and linear or logarithmic. Sieve is O(n log log n) and memory O(n). Fast exponentiation is O(log exponent). Combinatorics often needs precomputed factorials/inverses when modulo prime is involved. Geometry is often O(n^2) for pairwise anchor methods unless a stronger structure is available.

Cheat Sheet

Modulo:
    What remainder class matters?

GCD:
    What common divisor relation is preserved?

Sieve:
    What range is bounded enough to precompute?

Combinatorics:
    Am I counting choices, arrangements, or distributions?

Fast power:
    What happens when the exponent bit is 1?

Digits:
    What is the carry or place-value invariant?

Geometry:
    Can I avoid floating point?

Extended Translation Notes

Numeric problems need a clear invariant before code. The code is usually short; the hard part is choosing the correct property.

Step 1: Identify the Numeric Domain

SurfaceDomain
divisibilityremainders, gcd, factors
large countscombinatorics, modulo arithmetic
prime-related constraintsfactorization or sieve
powersexponent bits
digit stringsplace value and carry
coordinate geometrydistances, slopes, cross products

Step 2: Identify the Safe Reduction

A numeric reduction preserves the answer while simplifying the value.

Examples:

Modulo:
    replace value with value % m

GCD:
    replace (a, b) with (b, a % b)

Fast power:
    replace x^n with (x^2)^(n/2)

Slope:
    replace dy/dx with reduced pair (dy/g, dx/g)

Digit parsing:
    process value = value * base + digit

Step 3: Decide Representation

Representation choices often decide correctness.

NeedRepresentation
exact slopereduced integer pair
huge power modulo mrepeated modular multiplication
combinations modulo primefactorials and modular inverses
primality up to nboolean sieve
factor connectivityprime factor map
decimal parsingsign, value, bounds

Step 4: Handle Edge Cases Early

Always check:

zero
one
negative values
empty input
overflow risk
modulo with negative numbers
duplicate points
vertical or horizontal lines

Strategy Invariants

Modular Arithmetic

Invariant:

If two values have the same remainder modulo m, their difference is divisible
by m.

Use this for prefix sums, cyclic states, and large values reduced under a modulus.

GCD / LCM

Invariant:

gcd(a, b) preserves the set of common divisors through gcd(b, a % b).

LCM should be computed as:

a // gcd(a, b) * b

This reduces overflow risk.

Sieve and Factorization

Invariant:

Every composite number has a prime factor no larger than its square root.

Sieve is for many numbers in a bounded range. Trial division is acceptable for one number or small constraints.

Combinatorics

Invariant:

The formula counts each valid object exactly once.

Before using a formula, decide whether order matters:

combination: order does not matter
permutation: order matters
multiset: repeated items need division or DP

Digit Math

Invariant:

After processing a prefix of digits, value equals that prefix interpreted in
the chosen base.

For carry problems, the invariant is:

carry represents overflow from lower place values already processed.

Geometry

Invariant:

Integer formulas should preserve geometric relations without floating-point
rounding.

Prefer:

cross products
squared distances
reduced slopes
bounding-box overlap

Worked Problem Snapshots

Continuous Subarray Sum

State:

first index for each prefix remainder

Rule:

same remainder at indexes far enough apart gives a subarray sum divisible by k

Trap:

Subarray length must be at least 2.

Super Pow

State:

base modulo m and exponent digits

Rule:

a^(digits_so_far * 10 + d) = (a^digits_so_far)^10 * a^d

Engine:

modular fast exponentiation

Ugly Number

State:

current n after removing factors 2, 3, and 5

Invariant:

If all remaining factors are allowed, final n becomes 1.

Trap:

Handle n <= 0 as false.

Prime Factor Connectivity

State:

number nodes connected through shared prime factors

Engine:

factorization plus DSU

Trap:

Do not connect numbers by composite labels when prime labels are enough.

Pascal Triangle

State:

previous row

Rule:

row[i] = prev[i - 1] + prev[i]

Invariant:

Each row stores binomial coefficients for that row.

Add Binary

State:

i, j, carry

Rule:

bit = (a_bit + b_bit + carry) % 2
carry = total // 2

Trap:

Continue while carry remains, even if both strings are exhausted.

String to Integer

State:

sign, current value, index

Invariant:

value is the parsed numeric prefix before applying final sign.

Trap:

Clamp before overflowing fixed-width integer bounds in lower-level languages.

Valid Square

State:

six pairwise squared distances

Rule:

four equal positive sides and two equal larger diagonals

Trap:

Use squared distances, not floating-point square roots.

Max Points on a Line

State:

anchor point and normalized slope counts

Invariant:

Every point with the same reduced slope from the anchor lies on the same line
through that anchor.

Trap:

Handle duplicate points and vertical lines explicitly.

Dry Runs

Dry Run: GCD

Input:

a = 48
b = 18

Process:

gcd(48, 18)
gcd(18, 12)
gcd(12, 6)
gcd(6, 0)

Answer:

6

Dry Run: Fast Power

Input:

x = 2
n = 13

Binary exponent:

13 = 1101b

Process:

ans *= 2       because low bit is 1
square base -> 4
skip multiply because next bit is 0
square base -> 16
ans *= 16
square base -> 256
ans *= 256

Answer:

8192

Dry Run: Subarrays Divisible by K

Input:

nums = [4, 5, 0]
k = 5

Process:

start counts[0] = 1

prefix after 4: remainder 4, add counts[4] = 0
prefix after 5: remainder 4, add counts[4] = 1
prefix after 0: remainder 4, add counts[4] = 2

Answer:

3

Dry Run: Slope Normalization

Anchor:

(0, 0)

Points:

(2, 2) -> dy=2, dx=2 -> reduced (1, 1)
(4, 4) -> dy=4, dx=4 -> reduced (1, 1)
(1, 2) -> dy=2, dx=1 -> reduced (2, 1)

The first two points share the same line through the anchor.