C++ simple math


  • 0
    S

    As my wife explained to me, the next perfect square have the same difference from current as current from previous +2

    /* 
           number diff
           1      1
           4      3
           9      5
           16     7
           25     9
           36     11
           49     13
           64     15
           81     17
           100    19
         */
        bool isPerfectSquare(int num)
        {
            if (num < 1)
                return false;
                
            if (num == 1)
                return true;
    
            int currSq = 1;
            int diff = 1;
            
            while (currSq < num)
            {
                
                diff += 2;
                currSq += diff;
                
                // if overflow
                if (currSq < 0)
                    break;
            }
            
            if (currSq == num)
                return true;
            
            return false;
                
        }
    

Log in to reply
 

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