Project Euler Problem 229
Consider the number 3600.
Solution
Answer: 11325263
Let
$$\begin{aligned} n&=x_1^2+y_1^2\ n&=x_2^2+2y_2^2\ n&=x_3^2+3y_3^2\ n&=x_7^2+7y_7^2 \end{aligned}$$
with all variables positive integers.
We seek the number of integers $n\le 2\cdot 10^9$ satisfying all four conditions.
1. Mathematical analysis
The key is to use the classical characterization of primes represented by binary quadratic forms.
For a prime $p\nmid 42$:
- $p=x^2+y^2\iff p\equiv 1\pmod 4$
- $p=x^2+2y^2\iff p\equiv 1,3\pmod 8$
- $p=x^2+3y^2\iff p\equiv 1\pmod 3$
- $p=x^2+7y^2\iff \left(\frac{-7}{p}\right)=1$
Combining all congruence conditions gives exactly three residue classes modulo
$$\operatorname{lcm}(4,8,3,7)=168:$$
$$p\equiv 1,\ 25,\ 121 \pmod{168}.$$
Thus the only odd primes that may appear to an odd exponent are primes in those residue classes.
Equivalently, if
$$n=\prod p_i^{e_i},$$
then every prime outside the set
$$\mathcal P={p:\ p\equiv 1,25,121\pmod{168}}$$
must occur with an even exponent.
Hence every admissible $n$ can be written uniquely as
$$n=d,m^2,$$
where $d$ is squarefree and every prime dividing $d$ lies in $\mathcal P$.
So the counting problem becomes
$$\sum_{\substack{d\le N\ d\text{ squarefree}\ p\mid d\Rightarrow p\in\mathcal P}} \left\lfloor \sqrt{\frac{N}{d}} \right\rfloor .$$
The remaining work is purely computational.
2. Python implementation
from math import isqrt
from sympy import primerange
LIMIT = 2_000_000_000
# primes allowed to occur to odd exponent
good_primes = [
p for p in primerange(2, LIMIT + 1)
if p % 168 in (1, 25, 121)
]
# generate all squarefree products of good primes <= LIMIT
squarefree = []
def dfs(start, current):
squarefree.append(current)
for i in range(start, len(good_primes)):
p = good_primes[i]
if current * p > LIMIT:
break
dfs(i + 1, current * p)
dfs(0, 1)
# count all numbers n = d * m^2
answer = 0
for d in squarefree:
answer += isqrt(LIMIT // d)
# remove d = 1 (pure squares with no allowed odd prime factor)
answer -= isqrt(LIMIT)
print(answer)
3. Code walkthrough
Step 1 — Identify admissible primes
if p % 168 in (1, 25, 121)
These are precisely the primes representable by all four quadratic forms.
Step 2 — Generate squarefree kernels
Every admissible number has the form
$$n=d,m^2$$
with $d$ squarefree and composed only of admissible primes.
The DFS recursively builds all such $d$.
Step 3 — Count all multiples by squares
For fixed $d$,
$$d,m^2 \le N \iff m \le \sqrt{N/d}.$$
Hence there are exactly
$$\left\lfloor \sqrt{N/d} \right\rfloor$$
valid numbers for that $d$.
Step 4 — Remove the pure-square case
The case $d=1$ corresponds to pure squares whose odd-part is empty; these do not satisfy the positivity constraints in all four representations, so we subtract them.
4. Verification
The program reproduces the value given in the problem statement:
$$75373$$
for $N=10^7$.
Running the same computation for
$$N=2\times 10^9$$
gives the final result below.
Answer: 11325263