题目:
Given a non-negative integer c
, your task is to decide whether there're two integers a
and b
such that a2 + b2 = c.
Example 1:
Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3 Output: False题目链接
题意:
给一个非负的整数c,判断是否存在两个整数a,b满足a2 + b2 = c。
c是非负的,所以a和b的取值可以为0,所以a和b取值应该是[0, sqrt(c)],从0到sqrt(c)枚举一遍,假如c-a*a开平方后可以整除1,那么说明此时的a,b满足条件。
代码如下:
class Solution {
public:
bool judgeSquareSum(int c) {
int temp = sqrt(c);
for (int i = 0; i <= temp; i ++) {
int j = c - i * i;
if (fmod(sqrt(j), 1.00) != 0) {
continue;
}
return true;
}
return false;
}
};