101 Logo
onenoughtone

Problem Statement

Square Number Decomposition

You are given a non-negative integer c. Your task is to determine whether there exist two integers a and b such that:

a² + b² = c

In other words, you need to decide if the given number can be expressed as the sum of two perfect squares.

Examples

Example 1:

Input: c = 5
Output: true
Explanation: 1² + 2² = 1 + 4 = 5

Example 2:

Input: c = 3
Output: false
Explanation: There are no two integers a and b such that a² + b² = 3

Example 3:

Input: c = 25
Output: true
Explanation: 3² + 4² = 9 + 16 = 25

Constraints

  • 0 <= c <= 2³¹ - 1

Problem Breakdown

To solve this problem, we need to:

  1. The problem can be approached using a two-pointer technique, starting from the smallest and largest possible values
  2. The maximum value of a or b cannot exceed the square root of c
  3. The problem is related to the Pythagorean theorem and Fermat's theorem on the sum of two squares
  4. A number can be expressed as the sum of two squares if and only if its prime factorization contains even powers of primes of the form 4k+3
  5. Binary search can be used to check if c - a² is a perfect square for each possible value of a
ProblemSolutionCode
101 Logo
onenoughtone