Count number of solutions of x^2 = 1 (mod p) in given range in C++

We are given with integers x and p. The goal is to find the number of solutions of the equation −x2=1 ( mod p ) such that x lies in range [1,N].

We will do this by traversing from 1 to N and take each number as x check if (x*x)%p==1. If yes then increment the count.

Let’s understand with examples.

Input − n=5, p=2

Output − Number of Solutions − 3

Explanation − Between the range 1 to 5.

12=1%2=1, count=1
22=4%2=0, count=1
32=9%2=1, count=2
42=16%2=0, count=2
52=25%2=1, count=3
Total number of solutions=3.

Input − n=3, p=4

Output − Number of Solutions − 2

Explanation − Between the range 1 to 3.

12=1%4=1, count=1
22=4%4=0, count=1
32=9%4=1, count=2
Total number of solutions=2

Approach used in the below program is as follows

  • We take two variables n and p.

  • Function solutionsCount(int n,int p) takes both parameters n and p and returns the number of solutions for equation: x2%p==1 (or x2=1 ( mod p ) ).

  • Starting from x=1 to x=n, check if x*x==1, if yes increment count.

  • At the end of the loop, count will have the number of solutions.

  • Return count as result.


 Live Demo

using namespace std;
int solutionsCount(int n, int p){
   int count = 0;
   for (int x=1; x<=n; x++){
      if ((x*x)%p == 1)
         { ++count; }
   return count;
int main(){
   int n = 8, p = 3;
   cout<<"Number of solutions :"<<solutionsCount(n, p);
   return 0;


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

Number of solutions : 6