charlesreid1.com blog

Project Euler 198 and Continued Fractions: When Is a Rational Ambiguous?

Posted in Mathematics

permalink

Project Euler problem 198 is a number theory problem that turns out to be almost entirely about continued fractions. The problem hides this - the statement talks about "ambiguous" real numbers - but the ambiguity has a clean characterization in terms of continued fraction expansions, and once you see it, the problem gets a lot smaller.

Wiki notes: Project Euler/198.

The Problem

Define a best approximation to a real number x with denominator bound d as a rational r/s in reduced form with s ≤ d, such that any other rational p/q closer to x than r/s has q > d. In other words: it is the rational number with the smallest denominator that gets as close to x as anything with a small enough denominator can.

Usually the best approximation is unique for each denominator bound. But sometimes there are two equally-good best approximations. The problem gives the example of x = 9/40, which has both 1/4 and 1/5 as best approximations for the denominator bound d = 6. Both are tied for closest to 9/40 among rationals with denominator at most 6.

Call a real number x ambiguous if there is at least one denominator bound for which it has two best approximations. Ambiguous numbers are necessarily rational.

The question: how many ambiguous x = p/q with 0 < x < 1/100 and q ≤ 10^8 are there?

Why Continued Fractions

Any real number x has a continued fraction expansion

$$ x = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{a_3 + \ddots}}} $$

which we write compactly as [a_0; a_1, a_2, a_3, ...]. For rational numbers, the expansion terminates. For irrationals, it does not.

The convergents of a continued fraction are the rationals you get by truncating the expansion at each step. The convergents of [a_0; a_1, a_2, ..., a_n] are

$$ [a_0], [a_0; a_1], [a_0; a_1, a_2], \ldots $$

There is a beautiful classical theorem that says: the convergents of the continued fraction expansion of x are exactly the best approximations to x. Every convergent is a best approximation for some denominator bound, and every best approximation is a convergent or a certain kind of intermediate fraction.

For x = 9/40:

  • CF expansion: [0; 4, 2, 4]
  • First convergent: [0; 4] = 1/4
  • Second convergent: [0; 4, 2] = 1 / (4 + 1/2) = 2/9
  • Third (final) convergent: [0; 4, 2, 4] = 9/40

So 1/4 is one best approximation for 9/40 at some bound. Where does the other one, 1/5, come from?

Where Ambiguity Comes From

The answer is that not all best approximations are convergents. There are also intermediate fractions, which sit between successive convergents. Specifically, when a partial quotient a_k is larger than 1, you can form intermediate fractions

$$ \frac{p_{k-1} + j \cdot p_k}{q_{k-1} + j \cdot q_k} $$

for j = 1, 2, ..., a_{k+1} - 1, where p_k / q_k is the k-th convergent. These intermediate fractions are best approximations for certain denominator bounds.

The situation where a real number has two best approximations for some denominator bound is exactly when a convergent and an intermediate fraction happen to sit equidistant from x. This can only happen when the continued fraction expansion has some partial quotient bigger than 1 sitting in the right place.

The clean characterization we ended up with is this:

A rational p/q is non-ambiguous if and only if its continued fraction expansion has the form

$$ [0; a_1] \quad \text{or} \quad [0; a_1, 1, 1, \ldots, 1] $$

Everything else is ambiguous.

This is the crux of the problem. Instead of counting ambiguous fractions directly, count the total number of relevant fractions and subtract the non-ambiguous ones - or, better, characterize the ambiguous ones directly by generating their continued fraction expansions.

Constraints From the Problem

The problem restricts to 0 < p/q < 1/100 and q ≤ 10^8.

Since p ≥ 1 and p/q < 1/100, we have q > 100 p ≥ 100. So q ranges from 101 up to 10^8.

For a given q, valid p values satisfy:

  • p ≥ 1
  • p ≤ q/100
  • gcd(p, q) = 1 (reduced form)

That gives us roughly q/100 candidate numerators per denominator, but we also have to intersect with "coprime to q" and "continued fraction has the right shape to be ambiguous."

The high-level approach:

  1. Iterate over denominators q from 101 to 10^8
  2. For each q, enumerate valid p values (coprime to q, in range)
  3. Compute the continued fraction expansion of p/q
  4. Check whether the expansion has the "ambiguous" shape
  5. Count

The bottleneck is that step 1 is 10^8 iterations, and even a very fast inner loop times out. So the real approach is to invert the problem: instead of iterating over fractions and checking whether their CF is ambiguous, iterate over the shapes of ambiguous CF expansions and count the fractions those shapes produce that fall in the range.

This is a nice example of a general technique: when you have a characterization of the objects you want to count in terms of some structural property, generating objects by structure is usually faster than filtering.

The Bigger Point

Problems that look purely computational often turn out to have a clean structural characterization hiding underneath. The PE 198 statement never mentions continued fractions - it's about "best approximations" and "ambiguous real numbers." But the moment you dig into what best approximation actually means for rationals, continued fractions appear naturally, and the entire problem reduces to counting fractions whose CF has a certain shape.

This kind of translation - from a definition in one language to a characterization in another - is where number theory earns its reputation for being satisfying. You start with "count the ambiguous fractions" and you end with "count the fractions whose CF is not of the form [0; a₁, 1, 1, ..., 1]," and the second version is much easier to work with.

References

Project Euler 60: Finding Five Primes That Concatenate to Primes

Posted in Mathematics

permalink

Project Euler problem 60 is a nice mid-difficulty combinatorial search problem. It has enough structure that pure brute force falls over, and enough structure that a handful of small observations gives you a very tractable search.

Our working notes: Project Euler/60.

The Problem

The primes 3, 7, 109, and 673 are "quite remarkable" - concatenating any two of them in either order gives another prime. So 7109, 1097, 3673, 6733, 109673, 673109, and so on, are all prime. That is 12 concatenations, all prime.

The sum of these four primes is 792, and the problem states this is the smallest such sum for a set of four primes with this property.

Find the smallest sum for a set of five primes with the same property.

The Search Space

The naive approach: enumerate all 5-subsets of primes up to some bound and check the property. The number of concatenations to check per 5-subset is

$$ \binom{5}{2} \times 2 = 20 $$

which is fine. The problem is the number of 5-subsets. If your prime bound is 10,000, you have roughly 1,229 primes, and C(1229, 5) ≈ 2.3 × 10^13 subsets. Not fine.

So the whole game is: use structural facts about the problem to cut the search space down.

Pruning by Digit Constraints

The first observation is that concatenation preserves the last digit. If A and B are primes, and you form AB (concatenation), then the last digit of AB is the last digit of B. For AB to be prime, its last digit must be 1, 3, 7, or 9 (or 2 or 5, but those only work if the resulting number is exactly 2 or 5). So every prime in our set except possibly one small one has to end in 1, 3, 7, or 9.

Similarly, since every prime except 2 has an odd last digit, and prepending a number changes the first digit but not the last, both primes in a pair have to end in 1, 3, 7, or 9.

Also: 2 and 5 can be immediately ruled out from consideration - any concatenation involving 2 or 5 will produce a number ending in a digit other than 1/3/7/9, and therefore composite.

This is a small pruning at the level of "which primes to include," but it eliminates a lot of pointless primality tests later.

Two-Pronged Search Strategy

Here is where things get interesting. The problem hands us the known 4-prime solution {3, 7, 109, 673}. So we have two very different searches available to us:

Extend-known search. Take the known 4-prime set and look for a single 5th prime p such that p concatenates to a prime with each of {3, 7, 109, 673} in both orders. This is 8 primality checks per candidate p, and we only need to iterate over primes.

Fresh-set search. Look for a completely new set of 5 primes, possibly with a smaller total sum than the extension of the known 4-prime set.

The extend-known search is much cheaper (linear in the number of candidate 5th primes, versus quintic in the fresh-set search). It also gives you a solution quickly, which lets you set an upper bound on the answer, which lets you prune the fresh-set search dramatically.

The correct order is:

  1. Run extend-known first. Get some 5-prime solution and its sum, S*.
  2. Run fresh-set search but throw out any partial set whose sum already exceeds S*.

By the time you get to step 2, you have a hard bound on how big any of the primes can be, which shrinks the search space by orders of magnitude.

Even with the sum bound from step 1, a fresh search benefits from being built up incrementally rather than as a nested 5-deep loop:

  • Precompute a list of candidate primes up to some bound
  • Build a compatibility graph: nodes are primes, an edge exists between p and q if both p||q and q||p are prime
  • Find 5-cliques in this graph

Because a valid 5-set has to be a 5-clique in the compatibility graph (every pair has to concatenate-to-prime with every other pair), you can extend candidate sets incrementally:

  • Start with a 2-clique (pair of primes that concatenate-to-prime)
  • Extend to a 3-clique by finding a prime that concatenates-to-prime with both
  • Extend to 4, then 5

At each stage, the set of viable extensions shrinks fast. Most 2-cliques have no valid extension to a 3-clique. Most 3-cliques don't extend to a 4-clique. By the time you're looking for a 5-clique, the search is narrow.

Primality Testing

For a problem like this, the primality test gets called a lot. Two things worth doing:

  • Precompute a prime sieve for small numbers. The Sieve of Eratosthenes up to some reasonable bound gives you O(1) primality tests for anything in range.
  • For the concatenated numbers (which can get large), use a probabilistic test like Miller-Rabin. Deterministic for numbers under 3.3 × 10^14 with the right witness set, so no false positives in the range this problem cares about.

What We Learned

Two takeaways from this problem, generalizable to other combinatorial search puzzles:

Use the known solution as a bound. If the problem hands you a partial solution, get an answer from extending it first, then use that answer's sum/cost as a pruning bound for the fuller search. This is almost always faster than starting the fuller search cold.

Build the compatibility graph explicitly. For problems where "sets of k things all pairwise satisfy some property" is the search shape, converting it to "find a k-clique" in a precomputed compatibility graph is usually the right structure. Clique-finding is NP-hard in general, but for the small k values Project Euler cares about (5 in this case), it is fast in practice.

References

Tags:    project euler    primes    combinatorial search    brute force   

Two Burp Suite Extensions Worth Installing: JWT Editor and Hackvertor

Posted in Security

permalink

Short post, high signal-to-noise. If you're using Burp Suite for web security testing, there are two extensions we install on every fresh Burp installation before doing anything else. Both are free, both are in the official BApp Store, both take about thirty seconds to install, and both will save you hours the first time you need them.

Wiki reference: Burp Suite/Extensions.

How To Install BApp Store Extensions

For anyone who hasn't installed a Burp extension before:

  1. In Burp, go to Extensions → BApp Store
  2. Search for the extension name
  3. Click "Install"
  4. Wait for it to appear in the Installed tab

You can also install manually from a JAR file: Extensions → BApp Store → Manual install at the bottom, pick the file, click Open.

Extension 1: JWT Editor

JWT Editor on the BApp Store

JWT Editor lets you view and edit the contents of JSON Web Tokens in-flight. If a request contains a JWT in an Authorization: Bearer ... header or a cookie, JWT Editor gives you a tab that shows the decoded header and payload, lets you edit either one, and re-encodes and re-signs the token on the way out.

Why it matters: JWTs are opaque strings of base64 to the naked eye. If you want to test what happens when the role claim in the payload changes from user to admin, or what the server does when you swap the signing algorithm from RS256 to none, JWT Editor is the tool.

Without it: you're manually base64-decoding, editing JSON in a text editor, base64-encoding, and pasting the result back into the request. Every time. For every request.

With it: you edit the JSON in a form, and Burp handles the rest.

Extension 2: Hackvertor

Hackvertor on the BApp Store

Hackvertor is a tag-based conversion tool. You write tags in your request payloads that get expanded before the request goes out - things like URL-encode this, base64-encode that, MD5-hash the other thing, ROT13 the result, and so on. Tags can be nested and chained.

The killer feature is bypassing weak Web Application Firewalls. Many WAFs look for specific attack patterns - the literal string UNION SELECT, for example, or the literal string <script>. Hackvertor lets you write your payload once, then wrap it in a chain of encoding tags that produces a request the WAF doesn't recognize but the target application still parses correctly.

If you're doing any serious SQL injection or XSS testing against real-world targets, Hackvertor turns "the WAF blocked me" into "the WAF blocked one shape of my payload."

Other Extensions Worth Knowing About

We won't cover them here, but a few more from the BApp Store that come up regularly:

  • Autorize - automated access control testing
  • Turbo Intruder - much faster than the built-in Intruder for high-request-count attacks
  • Logger++ - richer request logging than the built-in HTTP history

Our full list, with notes on when each one matters, is on the Burp Suite/Extensions wiki page.

References

Tags:    security    burp suite    extensions    jwt    encoding    portswigger   

November 2026

Baby Mac Crypto

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

November 2017

A Hard(y) Math Problem