The Wayback Machine - https://web.archive.org/web/20240703214230/https://www.geeksforgeeks.org/find-square-root-under-modulo-p-set-1-when-p-is-in-form-of-4i-3/
Open In App

Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)

Last Updated : 03 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, … etc,
Examples: 

Input:  n = 2, p = 7
Output: 3 or 4
Explanation: 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

Naive Solution: Try all numbers from 2 to p-1. And for every number x, check if x is the square root of n under modulo p. 

 Below is the implementation of the above approach:

C++




// A Simple C++ program to find square root under modulo p
// when p is 7, 11, 19, 23, 31, ... etc,
#include <iostream>
using namespace std;
 
// Returns true if square root of n under modulo p exists
void squareRoot(int n, int p)
{
    n = n % p;
 
    // One by one check all numbers from 2 to p-1
    for (int x = 2; x < p; x++) {
        if ((x * x) % p == n) {
            cout << "Square root is " << x;
            return;
        }
    }
    cout << "Square root doesn't exist";
}
 
// Driver program to test
int main()
{
    int p = 7;
    int n = 2;
    squareRoot(n, p);
    return 0;
}


Java




// A Simple Java program to find square
// root under modulo p when p is 7,
// 11, 19, 23, 31, ... etc,
import java .io.*;
 
class GFG {
 
    // Returns true if square root of n
    // under modulo p exists
    static void squareRoot(int n, int p)
    {
        n = n % p;
     
        // One by one check all numbers
        // from 2 to p-1
        for (int x = 2; x < p; x++) {
            if ((x * x) % p == n) {
                System.out.println("Square "
                    + "root is " + x);
                return;
            }
        }
        System.out.println("Square root "
                + "doesn't exist");
    }
     
    // Driver Code
    public static void main(String[] args)
    {
        int p = 7;
        int n = 2;
        squareRoot(n, p);
    }
}
 
// This code is contributed by Anuj_67


Python3




# A Simple Python program to find square
# root under modulo p when p is 7, 11,
# 19, 23, 31, ... etc,
 
# Returns true if square root of n under
# modulo p exists
def squareRoot(n, p):
 
    n = n % p
     
    # One by one check all numbers from
    # 2 to p-1
    for x in range (2, p):
        if ((x * x) % p == n) :
            print( "Square root is ", x)
            return
 
    print( "Square root doesn't exist")
 
# Driver program to test
p = 7
n = 2
squareRoot(n, p)
 
# This code is Contributed by Anuj_67


C#




// A Simple C# program to find square
// root under modulo p when p is 7,
// 11, 19, 23, 31, ... etc,
using System;
 
class GFG {
 
    // Returns true if square root of n
    // under modulo p exists
    static void squareRoot(int n, int p)
    {
        n = n % p;
     
        // One by one check all numbers
        // from 2 to p-1
        for (int x = 2; x < p; x++) {
            if ((x * x) % p == n) {
                Console.Write("Square "
                     + "root is " + x);
                return;
            }
        }
        Console.Write("Square root "
                   + "doesn't exist");
    }
     
    // Driver Code
    static void Main()
    {
        int p = 7;
        int n = 2;
        squareRoot(n, p);
    }
}
 
// This code is contributed by Anuj_67


PHP




<?php
// A Simple PHP program to find
// square root under modulo p
// when p is 7, 11, 19, 23, 31,
// ... etc,
 
// Returns true if square
// root of n under modulo
// p exists
function squareRoot($n, $p)
{
    $n = $n % $p;
 
    // One by one check all
    // numbers from 2 to p-1
    for ($x = 2; $x < $p; $x++)
    {
        if (($x * $x) % $p == $n)
        {
            echo("Square root is " . $x);
            return;
        }
    }
    echo("Square root doesn't exist");
}
 
// Driver Code
$p = 7;
$n = 2;
squareRoot($n, $p);
 
// This code is contributed by Ajit.
?>


Javascript




<script>
// A Simple Javascript program to find square
// root under modulo p when p is 7,
// 11, 19, 23, 31, ... etc,
 
    // Returns true if square root of n
    // under modulo p exists
    function squareRoot(n,p)
    {
         n = n % p;
       
        // One by one check all numbers
        // from 2 to p-1
        for (let x = 2; x < p; x++) {
            if ((x * x) % p == n) {
                document.write("Square "
                    + "root is " + x);
                return;
            }
        }
        document.write("Square root "
                + "doesn't exist");
    }
     
    // Driver Code
    let p = 7;
    let n = 2;
    squareRoot(n, p);
     
    // This code is contributed by rag2127
     
</script>


Time Complexity: O(p)
Auxiliary Space: O(1)

Direct Method: If p is in the form of 4*i + 3, then there exist a Quick way of finding square root. 
 

If n is in the form 4*i + 3 with i >= 1 (OR p % 4 = 3)
And 
If Square root of n exists, then it must be
        ±n(p + 1)/4

Below is the implementation of the above idea : 

C++




// An efficient C++ program to find square root under
// modulo p when p is 7, 11, 19, 23, 31, ... etc.
#include <iostream>
using namespace std;
 
// Utility function to do modular exponentiation.
// It returns (x^y) % p.
int power(int x, int y, int p)
{
    int res = 1; // Initialize result
    x = x % p; // Update x if it is more than or
    // equal to p
 
    while (y > 0)
    {
       
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Returns true if square root of n under modulo p exists
// Assumption: p is of the form 3*i + 4 where i >= 1
void squareRoot(int n, int p)
{
    if (p % 4 != 3) {
        cout << "Invalid Input";
        return;
    }
 
    // Try "+(n^((p + 1)/4))"
    n = n % p;
    int x = power(n, (p + 1) / 4, p);
    if ((x * x) % p == n) {
        cout << "Square root is " << x;
        return;
    }
 
    // Try "-(n ^ ((p + 1)/4))"
    x = p - x;
    if ((x * x) % p == n) {
        cout << "Square root is " << x;
        return;
    }
 
    // If none of the above two work, then
    // square root doesn't exist
    cout << "Square root doesn't exist ";
}
 
// Driver program to test
int main()
{
    int p = 7;
    int n = 2;
    squareRoot(n, p);
    return 0;
}


Java




// An efficient Java program to find square root under
// modulo p when p is 7, 11, 19, 23, 31, ... etc.
public class GFG {
 
 
// Utility function to do modular exponentiation.
// It returns (x^y) % p.
static int power(int x, int y, int p)
{
    int res = 1; // Initialize result
    x = x % p; // Update x if it is more than or
    // equal to p
 
    while (y > 0) {
        // If y is odd, multiply x with result
        if (y %2== 1)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Returns true if square root of n under modulo p exists
// Assumption: p is of the form 3*i + 4 where i >= 1
static void squareRoot(int n, int p)
{
    if (p % 4 != 3) {
        System.out.print("Invalid Input");
        return;
    }
 
    // Try "+(n^((p + 1)/4))"
    n = n % p;
    int x = power(n, (p + 1) / 4, p);
    if ((x * x) % p == n) {
        System.out.print("Square root is " + x);
        return;
    }
 
    // Try "-(n ^ ((p + 1)/4))"
    x = p - x;
    if ((x * x) % p == n) {
        System.out.print("Square root is " + x);
        return;
    }
 
    // If none of the above two work, then
    // square root doesn't exist
    System.out.print("Square root doesn't exist ");
}
 
// Driver program to test
   static public void main(String[] args) {
       int p = 7;
    int n = 2;
    squareRoot(n, p);
    }
}


Python3




# An efficient python3 program to find square root
# under modulo p when p is 7, 11, 19, 23, 31, ... etc.
 
# Utility function to do modular exponentiation.
# It returns (x^y) % p.
def power(x, y, p) :
 
    res = 1 # Initialize result
    x = x % p # Update x if it is more
              # than or equal to p
 
    while (y > 0):
         
        # If y is odd, multiply x with result
        if (y & 1):
            res = (res * x) % p
 
        # y must be even now
        y = y >> 1 # y = y/2
        x = (x * x) % p
 
    return res
 
# Returns true if square root of n under
# modulo p exists. Assumption: p is of the
# form 3*i + 4 where i >= 1
def squareRoot(n, p):
 
    if (p % 4 != 3) :
        print( "Invalid Input" )
        return
 
 
    # Try "+(n^((p + 1)/4))"
    n = n % p
    x = power(n, (p + 1) // 4, p)
    if ((x * x) % p == n):
        print( "Square root is ", x)
        return
 
    # Try "-(n ^ ((p + 1)/4))"
    x = p - x
    if ((x * x) % p == n):
        print( "Square root is ", x )
        return
 
    # If none of the above two work, then
    # square root doesn't exist
    print( "Square root doesn't exist " )
 
# Driver Code
p = 7
n = 2
squareRoot(n, p)
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// An efficient C# program to find square root under
// modulo p when p is 7, 11, 19, 23, 31, ... etc.
 
using System;
public class GFG {
  
// Utility function to do modular exponentiation.
// It returns (x^y) % p.
static int power(int x, int y, int p)
{
    int res = 1; // Initialize result
    x = x % p; // Update x if it is more than or
    // equal to p
  
    while (y > 0) {
        // If y is odd, multiply x with result
        if (y %2 == 1)
            res = (res * x) % p;
  
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
  
// Returns true if square root of n under modulo p exists
// Assumption: p is of the form 3*i + 4 where i >= 1
static void squareRoot(int n, int p)
{
    if (p % 4 != 3) {
        Console.Write("Invalid Input");
        return;
    }
  
    // Try "+(n^((p + 1)/4))"
    n = n % p;
    int x = power(n, (p + 1) / 4, p);
    if ((x * x) % p == n) {
        Console.Write("Square root is " + x);
        return;
    }
  
    // Try "-(n ^ ((p + 1)/4))"
    x = p - x;
    if ((x * x) % p == n) {
        Console.Write("Square root is " + x);
        return;
    }
  
    // If none of the above two work, then
    // square root doesn't exist
    Console.Write("Square root doesn't exist ");
}
  
// Driver program to test
   static public void Main() {
       int p = 7;
    int n = 2;
    squareRoot(n, p);
    }
}
// This code is contributed by Ita_c.


PHP




<?php
// An efficient PHP program
// to find square root under
// modulo p when p is 7, 11,
// 19, 23, 31, ... etc.
 
// Utility function to do
// modular exponentiation.
// It returns (x^y) % p.
function power($x, $y, $p)
{
     
    // Initialize result
    $res = 1;    
     
    // Update x if it
    // is more than or
    // equal to p
    $x = $x % $p;
 
    while ($y > 0)
    {
         
        // If y is odd, multiply
        // x with result
        if ($y & 1)
            $res = ($res * $x) % $p;
 
        // y must be even now
        // y = y/2
        $y = $y >> 1;
        $x = ($x * $x) % $p;
    }
    return $res;
}
 
// Returns true if square root
// of n under modulo p exists
// Assumption: p is of the
// form 3*i + 4 where i >= 1
function squareRoot($n, $p)
{
    if ($p % 4 != 3)
    {
        echo "Invalid Input";
        return;
    }
 
    // Try "+(n^((p + 1)/4))"
    $n = $n % $p;
    $x = power($n, ($p + 1) / 4, $p);
    if (($x * $x) % $p == $n)
    {
        echo "Square root is ", $x;
        return;
    }
 
    // Try "-(n ^ ((p + 1)/4))"
    $x = $p - $x;
    if (($x * $x) % $p == $n)
    {
        echo "Square root is ", $x;
        return;
    }
 
    // If none of the above
    // two work, then square
    // root doesn't exist
    echo "Square root doesn't exist ";
}
 
    // Driver Code
    $p = 7;
    $n = 2;
    squareRoot($n, $p);
 
// This code is contributed by ajit
?>


Javascript




<script>
// An efficient Javascript program to find square root under
// modulo p when p is 7, 11, 19, 23, 31, ... etc.
     
    // Utility function to do modular exponentiation.
    // It returns (x^y) % p.
    function power(x,y,p)
    {
        let res = 1; // Initialize result
        x = x % p; // Update x if it is more than or
        // equal to p
      
        while (y > 0)
        {
         
            // If y is odd, multiply x with result
            if (y %2== 1)
                res = (res * x) % p;
      
            // y must be even now
            y = y >> 1; // y = y/2
            x = (x * x) % p;
        }
        return res;
    }
     
    // Returns true if square root of n under modulo p exists
    // Assumption: p is of the form 3*i + 4 where i >= 1
    function squareRoot(n, p)
    {
        if (p % 4 != 3)
        {
            document.write("Invalid Input");
            return;
        }
      
        // Try "+(n^((p + 1)/4))"
        n = n % p;
        let x = power(n, Math.floor((p + 1) / 4), p);
        if ((x * x) % p == n) {
            document.write("Square root is " + x);
            return;
        }
      
        // Try "-(n ^ ((p + 1)/4))"
        x = p - x;
        if ((x * x) % p == n) {
            document.write("Square root is " + x);
            return;
        }
      
        // If none of the above two work, then
        // square root doesn't exist
        document.write("Square root doesn't exist ");
    }
     
    // Driver program to test
    let p = 7;
    let n = 2;
    squareRoot(n, p);
     
    // This code is contributed by avanitrachhadiya2155
</script>


Time Complexity: O(Log p)
Auxiliary Space: O(1)

How does this work? 
We have discussed Euler’s Criterion in the previous post.
 

As per Euler's criterion, if square root exists, then 
following condition is true
 n(p-1)/2 % p = 1

Multiplying both sides with n, we get
 n(p+1)/2 % p = n % p  ------ (1)

Let x be the modulo square root. We can write,
  (x * x) ? n mod p
  (x * x) ? n(p+1)/2  [Using (1) given above]
  (x * x) ? n(2i + 2) [Replacing n = 4*i + 3]
        x ? ±n(i + 1)  [Taking Square root of both sides]
        x ? ±n(p + 1)/4 [Putting 4*i + 3 = p or i = (p-3)/4]

We will soon be discussing methods when p is not in above form.



Previous Article
Next Article

Similar Reads

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). Examples: Inp
15+ min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. Examples: 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 di
15+ min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a number x such that (x*x)%7 is 2. The number is 3.
11 min read
Equalizing array using increment under modulo 3
Given an array A containing N non-negative integers. Only following operation can be performed on the array: A[i] = ( A[i] + 1 ) % 3 where A[i] is the element of array A at index i, and performing this operation once costs 1 unit. Find the minimum cost to make all elements equal. Examples : Input : 1 0 3 2 Output : 4 units Explanation: First 3 is c
14 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Compute n! under modulo p
Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally ne
15+ min read
Multiply large integers under large modulo
Given an integer a, b, m. Find (a * b ) mod m, where a, b may be large and their direct multiplication may cause overflow. However, they are smaller than half of the maximum allowed long long int value. Examples: Input: a = 426, b = 964, m = 235Output: 119Explanation: (426 * 964) % 235 = 410664 % 235 = 119 Input: a = 10123465234878998, b = 65746311
7 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Primitive root of a prime number n modulo n
Given a prime number n, the task is to find its primitive root under modulo n. The primitive root of a prime number n is an integer r between[1, n-1] such that the values of r^x(mod n) where x is in the range[0, n-2] are different. Return -1 if n is a non-prime number. Examples: Input : 7 Output : Smallest primitive root = 3 Explanation: n = 7 3^0(
15 min read
three90RightbarBannerImg