用 C++ 统计平方和为 N 的数对 (a, b) 的个数
给定一个数字 N。目标是找到正数的有序对,使得它们的平方和为 N。
我们将通过找到方程 a2+ b2 = N 的解来做到这一点。其中 a 不大于 N 的平方根,b 可以计算为 (N-a2) 的平方根。
让我们用例子来理解。
输入
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 的有序对的个数。
将初始变量 count 设为 0,表示对数。
使用 for 循环遍历以查找 a。
从 a=1 开始到 a<=sqrt(n),即 n 的平方根。
计算 b 的平方为 n-pow(a,2)。
计算 b 为 sqrt(bsquare)
如果 pow(b,2)==bsquare。将 count 加 1。
在所有循环结束时,count 将包含此类对的总数。
返回 count 作为结果。
示例
#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; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行以上代码,它将生成以下输出:
Count of pairs of (a,b) where a^2+b^2=N: 122
广告