Find Square Root under Modulo p | (When p is product of two primes in the form 4*i + 3)
Given an integer N and an integer P denoting the product of two primes, the task is to find all possible Square Root of N under modulo P if it exists. It is given that P is the product of p1 and p2, where p1 and p2 are prime numbers of the form 4i + 3 where i is any integer. Some examples of such prime numbers are (7, 11, 19, 23, 31).
Input: N = 67, P = 77
Output: 23 65 12 54
All possible answers are (23, 65, 12, 54)
Input: N = 188, P = 437
Output: 25 44 393 412
All possible answers are (25, 44, 393, 412)
The simplest approach to solve this problem is to consider all numbers from 2 to P – 1 and for every number, check if it is the square root of N under modulo P. If found to be true, then print that number and break.
Time Complexity: O(P)
Auxiliary Space: O(1)
To optimize the above approach, the idea is to use Prime Factorization to obtain two factors p1 and p2 and then find square root of both using Square root under mod P. Then use Chinese Remainder Theorem to find the square root modulo p1 * p2. Each set will contain two equations (as there are two square roots each for modulo p1 and p2). Combining them all, four sets of equations are obtained which gives the four possible answers.
Follow the steps below to solve this problem:
- Factorize the number P by using Prime Factorization. Factors will be two primes p1 and p2.
- Find square root modulo primes p1 and p2.
- Two sets for answers is found, one for each prime. Each set containing two numbers.
- So there will be 4 set of equations if one number from each set is chosen.
- Perform Chinese Remainder Theorem to find the square root modulo p1 * p2 and print them.
Below is the implementation of the above approach where BigInteger class in Java is used to handle very large numbers:
25 44 393 412
Time Complexity: O(√P + logN)
Auxiliary Space: O(1)
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.