Count Distinct Non-Negative Integer Pairs (x, y) that Satisfy the Inequality x*x + y*y < n in C++


We are given a positive integer N. The goal is to count the pairs of distinct non-negative positive integers that satisfy the inequality − x*x + y*y < N.

We will start from x=0 to x2 lt; N and y=0 to y2 < N . If any x2 + y2 < N, increase count of pairs.

Let us understand with examples −

Input − n=4

Output − distinct pairs= 4

Explanation − pairs will be (0,0), (1,1), (0,1), (1,0). All these satisfy the inequality x2 + y2 < 4

Input −n=2

Output − distinct pairs= 3

Explanation &minus pairs will be (0,0), (0,1), (1,0). All these satisfy the inequality x2 + y2 < 2

Approach used in the below program is as follows

  • The integer N stores the positive integer.

  • Function countPairs(int n) takes n as input and returns the count of distinct non-negative positive integer pairs that satisfy the inequality −x2 + y2 < n.

  • count stores the number of such pairs , initially 0.

  • Start from i=0 to i2 < n and other loop j=0 to j2 < n.

  • If i2 + j2 < n increment count.

  • Return count in the end as result.

Example

 Live Demo

#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;
}

Output

If we run the above code it will generate the following output −

Distinct Non-Negative integer pairs count: 4

Updated on: 13-Aug-2020

151 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements