← Home

633. Sum of Square Numbers

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
633

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 633. Sum of Square Numbers, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • using sqrt function
  • time: O(sqrt(c) * log(c)), iterate sqrt(c) times, every iteration O(log(c)) to calculate sqrt
  • space: O(1)

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are judgeSquareSum, binary_search.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(sqrt(c) * log(c))
  • Space: O(log(c)), space used by binary search

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//using sqrt function
02//Runtime: 12 ms, faster than 25.09% of C++ online submissions for Sum of Square Numbers.
03//Memory Usage: 7.9 MB, less than 100.00% of C++ online submissions for Sum of Square Numbers.
04//time: O(sqrt(c) * log(c)), iterate sqrt(c) times, every iteration O(log(c)) to calculate sqrt
05//space: O(1)
06
07class Solution {
08public:
09    bool judgeSquareSum(int c) {
10        for(int i = 0; i <= int(sqrt(c/2)); i++){
11            if(sqrt(c - i*i) == int(sqrt(c - i*i))) return true;
12        }
13        return false;
14    }
15};
16
17//better brute-force
18//TLE
19//time: Time complexity : O(c). The total number of times the sumsum is updated is: 1 + 2 + 3 + ... + sqrt(c) = (1+sqrt(c))*sqrt(c)/2 = O(c)
20//Space complexity : O(1). Constant extra space is used. 
21
22class Solution {
23public:
24    bool judgeSquareSum(int c) {
25        for(long long a = 0; a*a <= c; a++){
26            int b = c - (int)a*a;
27            long long i = 1, sum = 0;
28            while(sum < b){
29                sum += i;
30                i += 2;
31            }
32            if(sum == (long long)b) return true;
33        }
34        return false;
35    }
36};
37
38//binary search
39//AddressSanitizer:DEADLYSIGNAL
40//time: O(sqrt(c) * log(c))
41//space: O(log(c)), space used by binary search
42
43class Solution {
44public:
45    bool binary_search(long long s, long long e, long long n){
46        if(s > e) return false;
47        long long mid = (s + e)/2;
48        if(mid * mid == n) return true;
49        if(mid * mid > n){
50            return binary_search(s, e-1, n);
51        }
52        return binary_search(s+1, e, n);
53    }
54    
55    bool judgeSquareSum(int c) {
56        for(long long a = 0; a * a <= (long long)c; a++){
57            long long b = c - (a*a);
58            if(binary_search(0, b, b)) return true;
59        }
60        return false;
61    }
62};
63
64//Fermat theorem
65//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Sum of Square Numbers.
66//Memory Usage: 8.1 MB, less than 100.00% of C++ online submissions for Sum of Square Numbers.
67//time: O(sqrt(c) * log(c)), sqrt(c) candidates of factor, a factor can occur at most log(c) times
68//space: O(1)
69class Solution {
70public:
71    bool judgeSquareSum(int c) {
72        //check for factor in the range [2, sqrt(c)]
73        for(int p = 2; p*p <= c; p++){
74            //p : candidate prime factor of c
75            int count = 0;
76            if(c % p == 0){ //p is a prime factor of c 
77                //every time we find a prime factor,
78                // we divide c by p so that c won't have p as factor anymore
79                //the maximum time a factor can occur is log(c)
80                while(c % p == 0){
81                    count++;
82                    c /= p;
83                }
84                if(p % 4 == 3 && count % 2 != 0){
85                    return false;
86                }
87            }
88        }
89        return c % 4 != 3;
90    }
91};

Cost

Complexity

Time
O(sqrt(c) * log(c))
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(log(c)), space used by binary search
Auxiliary state plus the answer structure where the problem requires one.