Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
1<sup>2</sup>=1%2=1, count=1 2<sup>2</sup>=4%2=0, count=1 3<sup>2</sup>=9%2=1, count=2 4<sup>2</sup>=16%2=0, count=2 5<sup>2</sup>=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.
1<sup>2</sup>=1%4=1, count=1 2<sup>2</sup>=4%4=0, count=1 3<sup>2</sup>=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.
Example
#include<bits/stdc++.h>
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;
}
Output
If we run the above code it will generate the following output −
Number of solutions : 6
