1. 程式人生 > >Sum of Square Numbers 平方數之和

Sum of Square Numbers 平方數之和

給定一個非負整數 c ,你要判斷是否存在兩個整數 a 和 b,使得 a2 + b2 = c。

示例1:

輸入: 5
輸出: True
解釋: 1 * 1 + 2 * 2 = 5

示例2:

輸入: 3
輸出: False

思路:因為要滿足a^2+b^2=c,所以a的取值範圍為[0,sqrt(c)],所以迴圈設定為[0,sqrt(c)],每次迴圈中我們反計算出b,b=sqrt(c-a^2),如果b是整數,那麼返回true,如果遍歷完都找不到滿足條件的b,那麼返回false。

參考程式碼:

class Solution {
public:
    bool judgeSquareSum(int c) {
        for (long long a = 0; a*a <= c; a++) {
            double b = sqrt(c - a * a);
            if (b == ((int)b)) {
                return true;
            }
        }
        return false;
    }
};