用 C++ 统计满足不等式 x*x + y*y < n 的不同非负整数对 (x, y) 的数量
给定一个正整数 N。目标是统计满足不等式:x*x + y*y < N 的不同非负整数对的数量。
我们将从 x=0 到 x2 < N 和 y=0 到 y2 < N 开始。如果任何 x2 + y2 < N,则增加对的数量。
输入
n=4
输出
distinct pairs= 4
说明 - 对将是 (0,0), (1,1), (0,1), (1,0)。所有这些都满足不等式 x2 + y2 < 4
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
n=2
输出
distinct pairs= 3
说明 - 对将是 (0,0), (0,1), (1,0)。所有这些都满足不等式 x2 + y2 < 2
下面程序中使用的算法如下
整数 N 存储正整数。
函数 countPairs(int n) 以 n 作为输入,并返回满足不等式:x2 + y2 < n 的不同非负整数对的数量。
count 存储此类对的数量,初始值为 0。
从 i=0 到 i2 < n 开始,另一个循环 j=0 到 j2 < n。
如果 i2 + j2 < n,则递增 count。
最后返回 count 作为结果。
示例
#include <iostream> using namespace std; int countPairs(int n){ int count = 0; for (int i = 0; i*i < n; i++) for (int j = 0; j*j < n; j++) //x*x + y*y < n if(i*i + j*j < n) count++; return count; } int main(){ int N=4; cout << "Distinct Non-Negative integer pairs count: " << countPairs(N) ; return 0; }
输出
Distinct Non-Negative integer pairs count: 4
广告