Given a non-negative integer c , your task is to decide whether there're two integers a and b such that a 2 + b 2 = c. Example 1: Input: 5 Output: true Explanation:1 2 + 2 2 = 5 Example 2: Input: 3 Output: false Source: LeetCode Solution in C++ The idea is simple: Instead of looking for all possible combinations of a and b. Iterate from 0 to sqrt(c), check if the result of c - a 2 is a perfect square, if so, we have found the combinations of sum of squares (a 2 + b 2 = c). class Solution { public: bool judgeSquareSum(int c) { for(int i=0;i<=(int)sqrt(c);++i) if(is_perfect_square(c-i*i)) //check is the number is perfect square return true; return false; } bool is_perfect_square (int num){ int sq = sqrt(num); return sq*sq == num; } };