Numbers with Double Sum-of-Squares Decompositions
Math & Bit ManipulationModel answerLast updated
Count unique pairs of non-negative integers whose squares sum to a target value, identifying numbers with exactly two representations up to a limit N.
Given a positive integer $N$, find all integers $x$ such that $1 \le x \le N$ and $x$ can be represented as the sum of two squares of non-negative integers ($x = a^2 + b^2$) in exactly two distinct ways.
Two decompositions are considered identical if they differ only by swapping the terms ($a^2 + b^2$ is the same as $b^2 + a^2$). However, different pairs $(a, b)$ with $0 \le a \le b$ are treated as distinct representations.
Function Signature
def find_two_sum_squares(N: int) -> List[int]:
Input & Output Constraints
- $1 \le N \le 1,000,000$
- Output must be a list of integers sorted in strictly ascending order.
Example 1
Input: N = 25
Output: [25]
Explanation:
- $25 = 0^2 + 5^2$
- $25 = 3^2 + 4^2$
There are no other valid decompositions for $25$. Thus, $25$ has exactly $2$ ways.
Example 2
Input: N = 50
Output: [25, 50]
Explanation:
- $25 = 0^2 + 5^2 = 3^2 + 4^2$ (2 ways)
- $50 = 1^2 + 7^2 = 5^2 + 5^2$ (2 ways)
Both $25$ and $50$ satisfy the condition and are returned in ascending order.
Hints
Hint 1
Rather than testing every candidate number x up to N by searching for pairs, generate all valid pairs (a, b) with 0 <= a <= b such that a^2 + b^2 <= N.
Hint 2
How can you avoid duplicate counting when a == b versus a < b? Enforcing 0 <= a <= b naturally generates each distinct unordered pair exactly once.
Hint 3
Since you only care if the count of valid representations is equal to 2, what is the most memory-efficient way to track counts up to N?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
Instead of trying to factor or decompose every number $x \le N$ from scratch, we can take a generative approach (a frequency sieve):
- Generate All Unordered Pairs: We iterate over all valid integer pairs $(a, b)$ such that $0 \le a \le b$ and $a^2 + b^2 \le N$. By enforcing $a \le b$, every unordered sum of two squares is produced exactly once.
- Frequency Array with Cap: We use a saturating counter array
countsof size $N + 1$. Since we only care if the frequency is exactly $2$, we can cap increments at $3$. - Memory Optimization: By using Python's
bytearray, each counter occupies only $1$ byte. For $N = 1,000,000$, this consumes approximately $1 \text{ MB}$ of memory, compared to $8+\text{ MB}$ for a standard list of integers. - Collect Result: After populating the table, scan from $x = 1$ to $N$ and append any index $x$ where
counts[x] == 2. This guarantees the output is naturally sorted.
Optimization on Loop Bounds
- The outer variable $a$ starts at $0$. Since $b \ge a$, the minimum sum for a given $a$ is $2a^2$. Hence, the outer loop runs while $2a^2 \le N$ ($a \le \lfloor\sqrt{N/2}\rfloor$).
- The inner variable $b$ ranges from $a$ to $\lfloor\sqrt{N - a^2}\rfloor$.
Python Source Code
from math import isqrt
from typing import List
def find_two_sum_squares(N: int) -> List[int]:
# counts[x] stores the number of ways to express x as a^2 + b^2 (0 <= a <= b).
# We saturate counts at 3 since we only care if count == 2.
counts = bytearray(N + 1)
a = 0
while 2 * a * a <= N:
a2 = a * a
max_b = isqrt(N - a2)
for b in range(a, max_b + 1):
x = a2 + b * b
if counts[x] < 3:
counts[x] += 1
a += 1
return [x for x in range(1, N + 1) if counts[x] == 2]
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$. The number of pairs $(a, b)$ visited corresponds to the integer lattice points in an eighth of a circle of radius $\sqrt{N}$. The number of pairs is approximately $\frac{\pi N}{8} \approx 0.393 N$. The final filtering pass takes $\mathcal{O}(N)$ time. Total operations for $N = 1,000,000$ are under $400,000$ loop iterations.
- Space Complexity: $\mathcal{O}(N)$. The
bytearrayrequires $N + 1$ bytes (~$1 \text{ MB}$ space for $N = 10^6$).
Common Pitfalls & Edge Cases
- Handling $a = b$: Counting representations by taking all $(a, b)$ and dividing the total count by $2$ fails when $a = b$ (e.g., $50 = 5^2 + 5^2$), as $(5, 5)$ has no distinct swapped pair. Enforcing $a \le b$ upfront avoids this issue completely.
- Including $a = 0$: Perfect squares like $25 = 0^2 + 5^2$ count as a valid representation. Ensure $a$ starts at $0$.
- Numbers with $\ge 3$ representations: $325 = 1^2 + 18^2 = 6^2 + 17^2 = 10^2 + 15^2$ has 3 representations. Capping count updates at $3$ ensures such numbers are excluded.
Follow-Up: Sum of Two Squares Theorem
If asked how to count representations using prime factorizations (e.g., for very large individual values of $x$ or $N = 10^{12}$):
- Express $x = 2^k \cdot \prod p_i^{e_i} \cdot \prod q_j^{f_j}$, where $p_i \equiv 1 \pmod 4$ and $q_j \equiv 3 \pmod 4$.
- $x$ can be represented as a sum of two squares if and only if every exponent $f_j$ is even.
- If valid, the number of distinct unordered non-negative representations is given by $\left\lceil \frac{B}{2} \right\rceil$, where $B = \prod (e_i + 1)$.
- For exactly $2$ representations, $B$ must equal $3$ or $4$. This requires the $p_i$ exponents to form either $p^2$, $p^3$, or $p \cdot q$ for prime factors $\equiv 1 \pmod 4$.