All puzzles › Math and Number Theory
Math and Number Theory Practice Problems
85 puzzles (33 easy, 44 medium, 8 hard), 18 free, in Python, JavaScript and C++.
Some problems are solved by a formula rather than a data structure. Greatest common divisors, prime tests, modular arithmetic, digit manipulation and a little geometry come up in interviews more than people expect, and each has a short standard solution worth knowing by heart.
How to spot a math and number theory problem
Suspect a math solution when the input is a single number rather than a collection, or when the limits are far too large to loop over. Write out the first few answers by hand. If a pattern appears, there is usually a closed form or a well known algorithm behind it.
The puzzles, easiest first
- A Market With No Market Maker (Easy, free): A decentralized exchange has no order book.
- A Promise From a Sorted List (Easy, free): Conformal prediction turns any model's guess into a range with a guarantee attached.
- How Much Does It Count? (Easy, free): Given an opponent's rating deviation, which is how unsure the ladder is about its rating, return how much its result should count, rounded to four decimal places.
- Nudge the Estimate (Easy, free): Q-learning keeps a number for each action: how good it expects that action to be.
- Shorter, Same Direction (Easy, free): One bad batch can produce a gradient so large that a single step wrecks the model.
- Spread the Beats Evenly (Easy, free): Place 3 drum hits as evenly as possible across 8 steps and you get the tresillo, the rhythm under a huge share of Latin and pop music.
- The Number Goes Stale (Easy, free): Given a player's rating deviation, their volatility, and how many rating periods they sat out, return their new deviation, rounded to two decimal places.
- Two Clocks, One Time (Easy, free): One clock chimes every m1 minutes and last chimed r1 minutes after the hour.
- What a Majority Has (Easy, free): In Raft, a leader copies its log to the other servers, and an entry is committed once a majority of the cluster has stored it.
- What Are the Odds? (Easy, free): Given your rating and a puzzle's rating, return your chance of solving it as a number between 0 and 1, rounded to four decimal places.
- Churn Rate (Easy): Given how many subscribers you started the month with and how many you lost, return the churn rate as a percentage, rounded to 1 decimal.
- Digit Sum (Easy): Given a number, return the sum of its digits.
- Digital Root (Easy): Given a number, add up its digits.
- Euclidean Distance (Easy): Given two points with any number of coordinates, return the straight-line distance between them, rounded to 3 decimals.
- Factorial (Easy): Given n, return n factorial: 1 x 2 x 3 x ...
- Gear Ratio (Easy): Given the tooth counts of the driver gear and the driven gear, return the gear ratio, rounded to 3 decimals.
- Greatest Common Divisor (Easy): Given two numbers a and b, return their greatest common divisor, the biggest number that divides both.
- Gross Margin (Easy): Given revenue and the cost of goods sold, return the gross margin as a percentage, rounded to 1 decimal.
- Halfway Between (Easy): Given two points in time, (ta, xa) and (tb, xb), and a time between them, return the position at that time, rounded to three decimal places.
- Interval in Semitones (Easy): Given two MIDI notes, return how many semitones apart they are.
- Is Quorum Met? (Easy): Given how many people showed up, the total number of seats, and the fraction needed, return true if there's a quorum.
- Least Common Multiple (Easy): Given two numbers, return their least common multiple, the smallest number both divide evenly.
- Mechanical Stress (Easy): Given a force in newtons and an area in square meters, return the stress in pascals, rounded to 2 decimals.
- Off One Edge, On the Other (Easy): Screen wrap turns the world into a loop: fly off the right edge and you come back on the left, as in Asteroids.
- Ohm's Law (Easy): Given current in amps and resistance in ohms, return the voltage, rounded to 2 decimals.
- Page and Offset (Easy): Given a virtual address and a page size in bytes, return [page number, offset within the page].
- Perfect Number (Easy): Given n, return true if it's a perfect number, meaning it equals the sum of its divisors other than itself.
- Return on Investment (Easy): Given gain and cost, return the return on investment as a percentage, rounded to 1 decimal.
- Sigmoid (Easy): Given a number x, return the sigmoid of x, rounded to 4 decimals.
- Statute Deadline (Easy): Given the day of an incident and the number of days allowed to file, return the last day a claim is still valid.
- Sum 1 to N (Easy): Given n, return the sum of every whole number from 1 to n.
- Train/Test Split (Easy): Given n samples and a training ratio, return [trainCount, testCount].
- Wait Longer Each Time (Easy): Given an attempt number (starting at 0), a base delay, and a cap, return how long to wait before retrying.
- A Shared Secret, Agreed in Public (Medium, free): With Diffie-Hellman, two strangers can agree on a secret number while an eavesdropper hears every word.
- Dividing When There Is No Division (Medium, free): In arithmetic modulo m, dividing by a means multiplying by its inverse: the number x with a times x leaving remainder 1.
- How Much Did We Learn? (Medium, free): Given your rating and a list of opponents, each with a rating and a deviation, return how much the batch told the ladder about you, as an estimated variance rounded to four decimal places.
- Lock With One Key, Open With Another (Medium, free): RSA has a public key anyone can encrypt with and a private key that only its owner can compute.
- Your New Rating (Medium, free): Given your rating and deviation, the puzzle's rating and deviation, and whether you solved it, return your new rating, rounded to two decimal places.
- A/B Test Winner (Medium): Given two pages as [visits, signups], return which one converts better (0 or 1), or -1 if they tie.
- Backface Culling (Medium): Given a triangle's three corners on screen, return true if it faces you.
- Barycentric Coordinates (Medium): Given a triangle's three corners a, b, and c and a point p, return p's barycentric weights [w0, w1, w2], rounded to 4 decimals.
- Batch Normalization (Medium): Given a batch of numbers, normalize them to a mean of 0 and a spread of 1, rounded to 3 decimals.
- Billable Rounding (Medium): Given the minutes worked, round UP to the next multiple of 6 and return that.
- Compound Interest (Medium): Given a starting amount, a yearly rate as a decimal, and a number of years, return the final amount, rounded to 2 decimals.
- Cosine Similarity (Medium): Given two vectors a and b, return their cosine similarity, rounded to 3 decimals.
- Count Divisors (Medium): Given n, return how many positive whole numbers divide it evenly.
- Count Parameters (Medium): Given the number of neurons in each layer, return the total trainable parameters.
- Cross-Entropy Loss (Medium): Given a list of predicted probabilities and the index of the true class, return the cross-entropy loss, rounded to 4 decimals.
- Customer Lifetime Value (Medium): Given the average order value, orders per year, and how many years a customer sticks around, return their lifetime value, rounded to 2 decimals.
- Dense Layer Forward (Medium): Given a weight matrix, a bias vector, and an input vector, return the layer's outputs, rounded to 3 decimals.
- Factorial Trailing Zeros (Medium): Given n, return how many zeros are at the end of n factorial, without computing it.
- Fold the Carry Back (Medium): Given a list of 16-bit numbers from a packet header, return its Internet checksum.
- GELU Activation (Medium): Given a list of numbers, apply the GELU activation to each one and return the results, rounded to 4 decimals.
- Intersection over Union (Medium): Given two boxes as [x1, y1, x2, y2], return their intersection over union, rounded to 3 decimals.
- Is It Prime? (Medium): Given n, return true if it's prime, meaning it's bigger than 1 and only divisible by 1 and itself.
- L2 Normalize (Medium): Given a vector, scale it to length 1 and return it, rounded to 3 decimals.
- Linear Interpolation (Medium): Given two points (x0, y0) and (x1, y1) and an x, return the y on the straight line between them, rounded to 3 decimals.
- Linear Prediction (Medium): Given weights, a bias, and an input x, return the model's prediction, rounded to 3 decimals.
- Logistic Prediction (Medium): Given weights, a bias, and an input x, return the predicted probability, rounded to 4 decimals.
- Markov Next State (Medium): Given a grid of transition counts and the current state, return the most likely next state.
- Mean Squared Error (Medium): Given predictions and targets, return the mean squared error, rounded to 3 decimals.
- MSE Gradient (Medium): Given predictions and targets, return the gradient of the mean squared error for each prediction, rounded to 3 decimals.
- Net Present Value (Medium): Given a discount rate and a list of yearly cash flows, starting with year 0, return the net present value, rounded to 2 decimals.
- Newton's Square Root (Medium): Given n, return its square root, rounded to 3 decimals, using Newton's method.
- Nth Fibonacci (Medium): Given n, return the nth Fibonacci number, where fib(0) is 0, fib(1) is 1, and every number after is the sum of the two before it.
- Pascal's Triangle Row (Medium): Given n, return row n of Pascal's triangle, starting from row 0, which is [1].
- Power (a^b) (Medium): Given a and b, return a to the power b.
- Power of Two? (Medium): Given n, return true if it's a power of two, like 1, 2, 4, or 8.
- R-Squared Score (Medium): Given predictions and actual targets, return the R-squared score, rounded to 3 decimals.
- Reverse Integer (Medium): Given a whole number, return it with its digits reversed and its sign kept.
- Root Mean Square (Medium): Given a list of readings, return the root mean square, rounded to 3 decimals.
- Sieve of Eratosthenes (Medium): Given n, return every prime up to and including n.
- Softmax (Medium): Given a list of scores, turn them into probabilities that add up to 1, rounded to 4 decimals.
- The Short Way Round (Medium): Given two headings in radians, return the smallest turn from the first to the second, rounded to four decimal places.
- Which Came Later (Medium): Given two 32-bit sequence numbers a and b, return true if a is newer than b.
- Which Diamond Did I Click? (Medium): In an isometric game, square map tiles are drawn as diamonds, so finding the tile under the mouse takes a little algebra.
- Z-Score Standardize (Medium): Given a list of numbers, return each one's z-score, rounded to 3 decimals.
- Any Few Pieces Open the Vault (Hard, free): A secret can be split so that any k people together can recover it and any fewer learn nothing.
- The Period Gives It Away (Hard, free): Shor's algorithm breaks RSA by turning factoring into finding a period.
- Which Pixels Are Inside (Hard, free): A GPU decides which pixels a triangle covers by testing each pixel's center against the three edges.
- Attention Weights (Hard): Given a query vector and a list of key vectors, return the attention weights, rounded to 4 decimals.
- Collatz Steps (Hard): Given n, return how many steps it takes to reach 1.
- Count Primes (Hard): Given n, return how many prime numbers are less than n.
- k-Means Assignment (Hard): Given a list of points and a list of centroids, return the index of the closest centroid for each point.
- Rotary Position Embedding (Hard): Given a vector, a position, and theta, rotate the vector and return it, rounded to 4 decimals.
Practice another pattern
Or browse by subject
Browse all 676 puzzles