Sum of Square Numbers

Updated on 30 June, 2025
Sum of Square Numbers header image

Problem Statement

Given a non-negative integer c, the task is to determine if there exist two integers, a and b, such that the sum of the squares of a and b equals c. This means one needs to confirm whether the equation a^2 + b^2 = c holds true for any pair of integers (a, b).

Examples

Example 1

Input:

c = 5

Output:

true

Explanation:

1 * 1 + 2 * 2 = 5

Example 2

Input:

c = 3

Output:

false

Constraints

  • 0 <= c <= 231 - 1

Approach and Intuition

The problem is essentially about finding if a given integer can be expressed as the sum of squares of two integers. The brute-force way to approach this would be to check all pairs (a, b) such that a^2 + b^2 could potentially equal c. However, we can optimize this process by leveraging some math and constraints:

  1. Since we know that squaring a number cannot be negative, both a and b should range from 0 to sqrt(c). This is because for any a or b greater than sqrt(c), a^2 or b^2 alone would be greater than c.

  2. Start with a = 0 and compute b^2 = c - a^2. If b^2 turns out to be a perfect square and b is an integer, then we have found such a pair, and we can return true. If not, increment a and check again.

  3. Continue this process until a > sqrt(c). If by the end no suitable pair (a, b) is found, return false.

This method ensures that we are not unnecessarily checking pairs that would obviously not satisfy the condition, hence optimizing our search space and time complexity.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    bool canBeSumOfSquares(int value) {
        for (int base = 2; base * base <= value; base++) {
            int factorCount = 0;
            while (value % base == 0) {
                factorCount++;
                value /= base;
            }
            if (base % 4 == 3 && factorCount % 2 != 0) return false;
        }
        return value % 4 != 3;
    }
};

The code provided addresses the problem of determining whether a given integer can be expressed as a sum of two square numbers. This solution is implemented in C++ within a class named Solution.

The method canBeSumOfSquares takes an integer value as input and uses a for loop to iterate through possible base numbers from 2 up to the square root of the value. Within the loop, a variable factorCount is initialized to zero to count the factors of value that match the current base.

During each iteration, while the remainder of the division of value by base is zero, factorCount is incremented, and value is divided by base. This while loop continues until value can no longer be divided by base without a remainder.

After exiting the while loop, the code checks if base, when modulo 4, equals 3 and factorCount is odd. If this condition is true, the function immediately returns false, indicating that value cannot be expressed as a sum of two squares under these conditions.

Finally, after the loop ends, the method returns true if value modulo 4 is not equal to 3, meaning the original input value or its residual factor, when tested, does not prohibit value from being expressed as the sum of two squares. Conversely, it returns false if any residual value does match the condition of being congruent to 3 modulo 4.

This function essentially utilizes mathematical properties specific to the quadratic forms and is effective in determining the sum of squares possibility under given constraints.

java
public class Solution {
    
    public boolean checkSquareSum(int target) {
        for (int num = 2; num * num <= target; num++) {
            int occurrence = 0;
            if (target % num == 0) {
                while (target % num == 0) {
                    occurrence++;
                    target /= num;
                }
                if (num % 4 == 3 && occurrence % 2 != 0) return false;
            }
        }
        return target % 4 != 3;
    }
}

This Java solution tackles the problem of checking if a given integer can be expressed as the sum of two square numbers. The solution leverages a mathematical insight related to the properties of prime factors of the number.

Here’s how the solution works:

  • The function checkSquareSum takes an integer target as its argument and checks if this number can be expressed as the sum of squares of two integers.
  • The method uses a for-loop to iterate through numbers, calculating their squares and checking if these squares are factors of the target.
  • For each number where num * num <= target, the loop checks the modulo of the target by this squared number.
  • If target % num equals zero, it implies that num is a factor, and the loop counts how many times num can divide the target evenly (occurrence).
  • A critical part of this checking involves a condition derived from a theorem in number theory: a number can be expressed as a sum of two squares if and only if at every prime factor of the form (4n + 3), the exponent is even.
  • Thus, if num % 4 == 3 and occurrence is odd, the function immediately returns false.
  • At the end of these checks, if the remaining target itself is a number of the form (4n + 3), the function will also return false.
  • If none of these conditions halt the function, it concludes that the number can be expressed as a sum of two squares and returns true.

This method effectively applies number theory to determine the possibility of expressing a number as a sum of squares, ensuring accuracy and efficiency by reducing unnecessary calculations.

python
class Solution:
    def checkSumSquare(self, value: int) -> bool:
        index = 2
        while index * index <= value:
            cnt = 0
            while value % index == 0:
                cnt += 1
                value //= index
            if index % 4 == 3 and cnt % 2 != 0:
                return False
            index += 1
        return value % 4 != 3

The given Python solution determines if a number can be expressed as the sum of squares of two integers. The function checkSumSquare checks this condition for the input value. Here's a breakdown of how the code works:

  1. Initialize index to 2 to start checking from the first prime number.
  2. Use a while loop to factorize the number by checking divisibility starting from the smallest prime.
  3. Initialize cnt to count how often value can be divided by index without leaving a remainder.
  4. For each divisor, if it leaves no remainder, increment cnt and reduce value by the divisor.
  5. If index modulo 4 equals 3 and cnt is odd, return False because a sum of squares representation is not possible under these conditions.
  6. Increment index to check the next integer.
  7. If the loop completes without finding a blocking condition, check the reduced value. If it's not of the form 4k + 3, return True.

Ultimately, the program returns True if the number can be represented as the sum of two squares and False otherwise. This method efficiently checks the sum of squares condition leveraging number theory properties related to the forms of prime factors.

Comments

No comments yet.