给我们一个数字N。目标是找到有序的正数对,使得它们的平方和为N。
我们将通过找到方程a 2 + b 2 = N的解来实现这一点。其中a不大于N的平方根,并且b可以计算为(Na 2)的平方根。
让我们通过示例来理解。
输入值
N=100
输出结果
Count of pairs of (a,b) where a^3+b^3=N: 2
说明
Pairs will be (6,8) and (8,6). 62+82=36+64=100
输入值
N=11
输出结果
Count of pairs of (a,b) where a^3+b^3=N: 0
说明
No such pairs possible.
我们取整数N。
函数squareSum(int n)取n并返回平方和为n的有序对的计数。
对的初始变量计数为0。
使用for循环遍历查找一个。
从a = 1到a <= sqrt(n),它是n的平方根。
将b的平方计算为n-pow(a,2)。
计算b为sqrt(bsquare)
如果pow(b,2)== bsquare。增量计数为1。
在所有循环结束时,计数将包含此类对的总数。
返回计数结果。
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int squareSum(int n){
int count = 0;
for (int a = 1; a <= sqrt(n); a++){
int bsquare=n - (pow(a,2));
int b = sqrt(bsquare);
if(pow(b,2)==bsquare){
count++; cout<<a;
}
}
return count;
}
int main(){
int N =5;
cout <<"Count of pairs of (a,b) where a^2+b^2=N: "<<squareSum(N);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs of (a,b) where a^2+b^2=N: 122