Count number of solutions of x^2 = 1 (mod p) in given range
Given two integers n and p, find the number of integral solutions to x2 = 1 (mod p) in the closed interval [1, n].
Input : n = 10, p = 5 Output : 4 There are four integers that satisfy the equation x2 = 1. The numbers are 1, 4, 6 and 9. Input : n = 15, p = 7 Output : 5 There are five integers that satisfy the equation x2 = 1. The numbers are 1, 8, 15, 6 and 13.
One simple solution is to go through all numbers from 1 to n. For every number, check if it satisfies the equation. We can avoid going through the whole range. The idea is based on the fact that if a number x satisfies the equation, then all numbers of the form x + i*p also satisfy the equation. We traverse for all numbers from 1 to p and for every number x that satisfies the equation, we find the count of numbers of the form x + i*p. To find the count, we first find the largest number for given x and then add (largest-number – x)/p to the result.
Below is the implementation of the idea.
This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.