用 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; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count of pairs of (a,b) where a^2+b^2=N: 122
廣告