Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++

We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their squares is N.

We will do this by finding solutions to the equation a2+ b2 = N. Where a is not more than square root of N and b can be calculated as square root of (N-a2).

Let’s understand with examples.




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




Count of pairs of (a,b) where a^3+b^3=N: 0


No such pairs possible.

Approach used in the below program is as follows

  • We take integer N.

  • Function squareSum(int n) takes n and returns the count of ordered pairs with sum of squares as n.

  • Take the initial variable count as 0 for pairs.

  • Traverse using for loop to find a.

  • Start from a=1 to a<=sqrt(n) which is square root of n.

  • Calculate square of b as n-pow(a,2).

  • Calculate b as sqrt(bsquare)

  • If pow(b,2)==bsquare. Increment count by 1.

  • At the end of all loops count will have a total number of such pairs.

  • Return the count as result.


 Live Demo

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


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

Count of pairs of (a,b) where a^2+b^2=N: 122