KatInterview

Numbers with Double Sum-of-Squares Decompositions

Math & Bit ManipulationModel answer

Last 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?