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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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.

Input

N=100

Output

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

Explanation

Pairs will be (6,8) and (8,6). 62+82=36+64=100

Input

N=11

Output

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

Explanation

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.

## Example

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

## Output

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