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

  1. A Market With No Market Maker (Easy, free): A decentralized exchange has no order book.
  2. A Promise From a Sorted List (Easy, free): Conformal prediction turns any model's guess into a range with a guarantee attached.
  3. 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.
  4. Nudge the Estimate (Easy, free): Q-learning keeps a number for each action: how good it expects that action to be.
  5. Shorter, Same Direction (Easy, free): One bad batch can produce a gradient so large that a single step wrecks the model.
  6. 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.
  7. 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.
  8. Two Clocks, One Time (Easy, free): One clock chimes every m1 minutes and last chimed r1 minutes after the hour.
  9. 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.
  10. 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.
  11. 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.
  12. Digit Sum (Easy): Given a number, return the sum of its digits.
  13. Digital Root (Easy): Given a number, add up its digits.
  14. Euclidean Distance (Easy): Given two points with any number of coordinates, return the straight-line distance between them, rounded to 3 decimals.
  15. Factorial (Easy): Given n, return n factorial: 1 x 2 x 3 x ...
  16. Gear Ratio (Easy): Given the tooth counts of the driver gear and the driven gear, return the gear ratio, rounded to 3 decimals.
  17. Greatest Common Divisor (Easy): Given two numbers a and b, return their greatest common divisor, the biggest number that divides both.
  18. Gross Margin (Easy): Given revenue and the cost of goods sold, return the gross margin as a percentage, rounded to 1 decimal.
  19. 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.
  20. Interval in Semitones (Easy): Given two MIDI notes, return how many semitones apart they are.
  21. 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.
  22. Least Common Multiple (Easy): Given two numbers, return their least common multiple, the smallest number both divide evenly.
  23. Mechanical Stress (Easy): Given a force in newtons and an area in square meters, return the stress in pascals, rounded to 2 decimals.
  24. 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.
  25. Ohm's Law (Easy): Given current in amps and resistance in ohms, return the voltage, rounded to 2 decimals.
  26. Page and Offset (Easy): Given a virtual address and a page size in bytes, return [page number, offset within the page].
  27. Perfect Number (Easy): Given n, return true if it's a perfect number, meaning it equals the sum of its divisors other than itself.
  28. Return on Investment (Easy): Given gain and cost, return the return on investment as a percentage, rounded to 1 decimal.
  29. Sigmoid (Easy): Given a number x, return the sigmoid of x, rounded to 4 decimals.
  30. 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.
  31. Sum 1 to N (Easy): Given n, return the sum of every whole number from 1 to n.
  32. Train/Test Split (Easy): Given n samples and a training ratio, return [trainCount, testCount].
  33. 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.
  34. 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.
  35. 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.
  36. 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.
  37. 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.
  38. 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.
  39. A/B Test Winner (Medium): Given two pages as [visits, signups], return which one converts better (0 or 1), or -1 if they tie.
  40. Backface Culling (Medium): Given a triangle's three corners on screen, return true if it faces you.
  41. 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.
  42. Batch Normalization (Medium): Given a batch of numbers, normalize them to a mean of 0 and a spread of 1, rounded to 3 decimals.
  43. Billable Rounding (Medium): Given the minutes worked, round UP to the next multiple of 6 and return that.
  44. 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.
  45. Cosine Similarity (Medium): Given two vectors a and b, return their cosine similarity, rounded to 3 decimals.
  46. Count Divisors (Medium): Given n, return how many positive whole numbers divide it evenly.
  47. Count Parameters (Medium): Given the number of neurons in each layer, return the total trainable parameters.
  48. 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.
  49. 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.
  50. Dense Layer Forward (Medium): Given a weight matrix, a bias vector, and an input vector, return the layer's outputs, rounded to 3 decimals.
  51. Factorial Trailing Zeros (Medium): Given n, return how many zeros are at the end of n factorial, without computing it.
  52. Fold the Carry Back (Medium): Given a list of 16-bit numbers from a packet header, return its Internet checksum.
  53. GELU Activation (Medium): Given a list of numbers, apply the GELU activation to each one and return the results, rounded to 4 decimals.
  54. Intersection over Union (Medium): Given two boxes as [x1, y1, x2, y2], return their intersection over union, rounded to 3 decimals.
  55. 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.
  56. L2 Normalize (Medium): Given a vector, scale it to length 1 and return it, rounded to 3 decimals.
  57. 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.
  58. Linear Prediction (Medium): Given weights, a bias, and an input x, return the model's prediction, rounded to 3 decimals.
  59. Logistic Prediction (Medium): Given weights, a bias, and an input x, return the predicted probability, rounded to 4 decimals.
  60. Markov Next State (Medium): Given a grid of transition counts and the current state, return the most likely next state.
  61. Mean Squared Error (Medium): Given predictions and targets, return the mean squared error, rounded to 3 decimals.
  62. MSE Gradient (Medium): Given predictions and targets, return the gradient of the mean squared error for each prediction, rounded to 3 decimals.
  63. 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.
  64. Newton's Square Root (Medium): Given n, return its square root, rounded to 3 decimals, using Newton's method.
  65. 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.
  66. Pascal's Triangle Row (Medium): Given n, return row n of Pascal's triangle, starting from row 0, which is [1].
  67. Power (a^b) (Medium): Given a and b, return a to the power b.
  68. Power of Two? (Medium): Given n, return true if it's a power of two, like 1, 2, 4, or 8.
  69. R-Squared Score (Medium): Given predictions and actual targets, return the R-squared score, rounded to 3 decimals.
  70. Reverse Integer (Medium): Given a whole number, return it with its digits reversed and its sign kept.
  71. Root Mean Square (Medium): Given a list of readings, return the root mean square, rounded to 3 decimals.
  72. Sieve of Eratosthenes (Medium): Given n, return every prime up to and including n.
  73. Softmax (Medium): Given a list of scores, turn them into probabilities that add up to 1, rounded to 4 decimals.
  74. 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.
  75. Which Came Later (Medium): Given two 32-bit sequence numbers a and b, return true if a is newer than b.
  76. 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.
  77. Z-Score Standardize (Medium): Given a list of numbers, return each one's z-score, rounded to 3 decimals.
  78. 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.
  79. The Period Gives It Away (Hard, free): Shor's algorithm breaks RSA by turning factoring into finding a period.
  80. Which Pixels Are Inside (Hard, free): A GPU decides which pixels a triangle covers by testing each pixel's center against the three edges.
  81. Attention Weights (Hard): Given a query vector and a list of key vectors, return the attention weights, rounded to 4 decimals.
  82. Collatz Steps (Hard): Given n, return how many steps it takes to reach 1.
  83. Count Primes (Hard): Given n, return how many prime numbers are less than n.
  84. k-Means Assignment (Hard): Given a list of points and a list of centroids, return the index of the closest centroid for each point.
  85. 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