我们给定一个正整数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
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递增计数。
最后返回计数结果。
#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