假设我们有一个非负整数c,我们必须确定是否有两个整数a和b满足a ^ 2 + b ^ 2 = c。
因此,如果输入类似于61,则输出将为True,因为61 = 5 ^ 2 + 6 ^ 2。
为了解决这个问题,我们将遵循以下步骤-
定义一个函数isPerfect(),这将需要x,
sr:= x的平方根
当(sr-sr的下限)为0时返回true
从主要方法中执行以下操作:
如果c与0相同,则-
返回真
对于初始化i:= 0,当i <c的平方根的上限时,更新(将i增加1),执行-
返回真
b:= c-i * i
如果isPerfect(b)为true,则-
返回假
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPerfect(int x){
long double sr = sqrt(x);
return ((sr - floor(sr)) == 0);
}
bool judgeSquareSum(int c) {
if (c == 0)
return true;
int b;
for (int i = 0; i < ceil(sqrt(c)); i++) {
b = c - i * i;
if (isPerfect(b))
return true;
}
return false;
}
};
main(){
Solution ob;
cout << (ob.judgeSquareSum(61));
}61
输出结果
1