4ms C++ code - Solve it mathematically

  • 37
    class Solution {  
        int is_square(int n){  
            int temp = (int) sqrt(n);  
            return temp * temp == n;  
        int numSquares(int n) {  
            while ((n & 3) == 0) //n%4 == 0  
                n >>= 2;  
            if ((n & 7) == 7) return 4; //n % 8 == 7  
            if(is_square(n)) return 1;  
            int sqrt_n = (int) sqrt(n);  
            for(int i = 1; i<= sqrt_n; i++){  
                if (is_square(n-i*i)) return 2;  
            return 3;  

    UPDATE: in order to understand, I suggest u read:

    here is the Lagrange's Four Square theorem - Limit the result to <= 4:

    And this article, in which you can also find the way to present a number as a sum of four squares:

  • 0

    Hi, sorry for bother you. But where can I find the strict math prove for this solution?

  • 0

    It is the most efficient solution, however it seems to be against what the problem want you to do.
    Anyway, it doesn't matter.

  • 2

    yeap, you are true that this solution seems not "natural" in thinking. It is not natural under a hidden context: Given 30 minutes of an interview. However, if it is under another context: Given your whole life, can you solve the problem?. Then other solution will be so trivial. Anyway, I think if we can prove the theorem ourselves, then we can proudly say that to our interviewers ^_^.

  • 2

    Agree, which is also pretty cooool.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.