

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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
- Related Questions & Answers
- Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n in C++
- Find value of y mod (2 raised to power x) in C++
- Find the number of integers x in range (1,N) for which x and x+1 have same number of divisors in C++
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. in C++
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find the Number of Solutions of n = x + n x using C++
- Count number of smallest elements in given range in C++
- Program to count number of ways we can fill 3 x n box with 2 x 1 dominos in Python
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++
- Find the number of solutions to the given equation in C++
- Print steps to make a number in form of 2^X – 1 in C Program.
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++
- Construct a frequency array of digits of the values obtained from x^1, x^2, ....., x^n in C++
- Find (1^n + 2^n + 3^n + 4^n) mod 5 in C++
- Sum of the series 1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + upto n terms in C++