Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists.
Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2, p = 5 Output: Square root doesn't exist
We have discussed Euler’s criterion to check if square root exists or not. We have also discussed a solution that works only when p is in form of 4*i + 3
In this post, Shank Tonelli’s algorithm is discussed that works for all types of inputs.
Algorithm steps to find modular square root using shank Tonelli’s algorithm :
1) Calculate n ^ ((p – 1) / 2) (mod p), it must be 1 or p-1, if it is p-1, then modular square root is not possible.
2) Then after write p-1 as (s * 2^e) for some integer s and e, where s must be an odd number and both s and e should be positive.
3) Then find a number q such that q ^ ((p – 1) / 2) (mod p) = -1
4) Initialize variable x, b, g and r by following values
x = n ^ ((s + 1) / 2 (first guess of square root) b = n ^ s g = q ^ s r = e (exponent e will decrease after each updation)
5) Now loop until m > 0 and update value of x, which will be our final answer.
Find least integer m such that b^(2^m) = 1(mod p) and 0 <= m <= r – 1 If m = 0, then we found correct answer and return x as result Else update x, b, g, r as below x = x * g ^ (2 ^ (r – m - 1)) b = b * g ^(2 ^ (r - m)) g = g ^ (2 ^ (r - m)) r = m
so if m becomes 0 or b becomes 1, we terminate and print the result. This loop guarantees to terminate because value of m is decreased each time after updation.
Following is C++ implementation of above algorithm.
Modular square root of 2 and 113 is 62
For more detail about above algorithm please visit :
For detail of example (2, 113) see :
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- 8086 program to find the square root of a perfect square root number | Set-2
- Euler's criterion (Check if square root under modulo p exists)
- MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
- 8085 program to find square root of a number
- 8086 program to find Square Root of a number
- Find square root of number upto given precision using binary search
- Primitive root of a prime number n modulo n
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Square root of a number using log
- Square root of an integer
- Babylonian method for square root
- Fast inverse square root
- Program to calculate Root Mean Square
- Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction)