The Wayback Machine - https://web.archive.org/web/20240930184628/https://www.geeksforgeeks.org/eulers-criterion-check-if-square-root-under-modulo-p-exists/
Open In App

Euler’s criterion (Check if square root under modulo p exists)

Last Updated : 01 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

A Naive Method is to try every number x where x varies from 2 to p-1. For every x, check if (x * x) % p is equal to n % p. 

C++




// A Simple C++ program to check if square root of a number
// under modulo p exists or not
#include<iostream>
using namespace std;
 
// Returns true if square root of n under modulo p exists
bool squareRootExists(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)
            return true;
    return false;
}
 
// Driver program to test
int main()
{
   int p = 7;
   int n = 2;
   squareRootExists(n, p)? cout << "Yes": cout << "No";
   return 0;
}


Java




// A Simple Java program to check if square
// root of a number under modulo p exists or not
import java.util.*;
class GFG
{
     
    // Returns true if square root of n under
    // modulo p exists
    static boolean squareRootExists(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)
                return true;
                 
        return false;
    }
     
    // Driver program to test
    public static void main (String[] args)
    {
         
        int p = 7;
        int n = 2;
         
        if(squareRootExists(n, p))
            System.out.print("Yes");
        else
            System.out.print("No"); 
    }
}
 
// This code is contributed by Anant Agarwal.


Python3




# A Simple Python 3 program to
# check if square root of a number
# under modulo p exists or not
 
# Returns true if square root of
# n under modulo p exists
def squareRootExists(n, p):
    n = n % p
 
    # One by one check all numbers
    # from 2 to p-1
    for x in range(2, p, 1):
        if ((x * x) % p == n):
            return True
    return False
 
# Driver Code
if __name__ == '__main__':
    p = 7
    n = 2
    if(squareRootExists(n, p) == True):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Surendra_Gangwar


C#




// A Simple C# program to check
// if square root of a number
// under modulo p exists or not
using System;
 
class GFG
{
     
    // Returns true if square root of 
    // n under modulo p exists
    static bool squareRootExists(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)
                return true;
                 
        return false;
    }
     
    // Driver code
    public static void Main ()
    {
         
        int p = 7;
        int n = 2;
         
        if(squareRootExists(n, p))
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by Sam007.


PHP




<?php
// A Simple PHP program to check
// if square root of a number
// under modulo p exists or not
 
// Returns true if square root
// of n under modulo p exists
function squareRootExists($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)
            return true;
    return false;
}
 
// Driver Code
$p = 7;
$n = 2;
if(squareRootExists($n, $p) == true)
    echo "Yes";
else
    echo "No";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
// A Simple Javascript program to check
// if square root of a number
// under modulo p exists or not
 
// Returns true if square root
// of n under modulo p exists
function squareRootExists(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)
            return true;
             
    return false;
}
 
// Driver Code
let p = 7;
let n = 2;
 
if (squareRootExists(n, p) === true)
    document.write("Yes");
else
    document.write("No");
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output : 

Yes

Time Complexity of this method is O(p).
Space Complexity: O(1) since only constant variables being used

This problem has a direct solution based on Euler’s Criterion. 
Euler’s criterion states that 

Square root of n under modulo p exists if and only if
n(p-1)/2 % p = 1

Here square root of n exists means is, there exist
an integer x such that (x * x) % p = 1

Below is implementation based on above criterion. Refer Modular Exponentiation for power function.

C++




// C++ program to check if square root of a number
// under modulo p exists or not
#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 there exists an integer x such
// that (x*x)%p = n%p
bool squareRootExists(int n, int p)
{
    // Check for Euler's criterion that is
    // [n ^ ((p-1)/2)] % p is 1 or not.
    if (power(n, (p-1)/2, p) == 1)
       return true;
 
    return false;
}
 
// Driver program to test
int main()
{
   int p = 7;
   int n = 2;
   squareRootExists(n, p)? cout << "Yes": cout << "No";
   return 0;
}


Java




// Java program to check if
// square root of a number
// under modulo p exists or not
import java.io.*;
 
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 & 1) == 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Returns true if there
// exists an integer x such
// that (x*x)%p = n%p
static boolean squareRootExists(int n,
                                int p)
{
    // Check for Euler's criterion
    // that is [n ^ ((p-1)/2)] % p
    // is 1 or not.
    if (power(n, (p - 1) / 2, p) == 1)
    return true;
 
    return false;
}
 
// Driver Code
public static void main (String[] args)
{
    int p = 7;
    int n = 2;
    if(squareRootExists(n, p))
        System.out.println ("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by ajit


Python3




# Python3 program to check if square root
# of a number under modulo p exists or not
 
# 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 there exists an integer
# x such that (x*x)%p = n%p
def squareRootExists(n, p):
     
    # Check for Euler's criterion that is
    # [n ^ ((p-1)/2)] % p is 1 or not.
    if (power(n, (int)((p - 1) / 2), p) == 1):
        return True
    return False
 
# Driver Code
p = 7
n = 2
if(squareRootExists(n, p) == True):
    print("Yes")
else:
    print("No")
 
# This code is contributed by Rajput-Ji


C#




// C# program to check if
// square root of a number
// under modulo p exists or not
using System;
 
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 & 1) == 0)
            res = (res * x) % p;
 
        // y must be even now
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
 
// Returns true if there
// exists an integer x such
// that (x*x)%p = n%p
static bool squareRootExists(int n,
                             int p)
{
    // Check for Euler's criterion
    // that is [n ^ ((p-1)/2)] % p
    // is 1 or not.
    if (power(n, (p - 1) / 2, p) == 1)
    return true;
 
    return false;
}
 
// Driver Code
static public void Main ()
{
    int p = 7;
    int n = 2;
    if(squareRootExists(n, p))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by m_kit


PHP




<?php
// PHP program to check
// if square root of a
// number under modulo
// p exists or not
 
// Utility function to
// do modular exponentiation
// It returns (x^y) % p.
function 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 there
// exists an integer x such
// that (x*x)%p = n%p
function squareRootExists($n, $p)
{
    // Check for Euler's criterion
    // that is [n ^ ((p-1)/2)] % p
    // is 1 or not.
    if (power($n, (int)(($p - 1) / 2),
                         $p) == 1)
    return true;
 
    return false;
}
 
// Driver Code
$p = 7;
$n = 2;
 
if(squareRootExists($n, $p) == true)
    echo "Yes";
else
    echo "No";
 
// This code is contributed by ajit
?>


Javascript




<script>
 
    // Javascript program to check if
    // square root of a number
    // under modulo p exists or not
     
    // 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 & 1) == 0)
                res = (res * x) % p;
 
            // y must be even now
            y = y >> 1; // y = y/2
            x = (x * x) % p;
        }
        return res;
    }
 
    // Returns true if there
    // exists an integer x such
    // that (x*x)%p = n%p
    function squareRootExists(n, p)
    {
        // Check for Euler's criterion
        // that is [n ^ ((p-1)/2)] % p
        // is 1 or not.
        if (power(n, (p - 1) / 2, p) == 1)
            return true;
 
        return false;
    }
     
    let p = 7;
    let n = 2;
    if(squareRootExists(n, p))
        document.write("Yes");
    else
        document.write("No");
 
</script>


Output : 

Yes

How does this work? 

If p is a prime, then it must be an odd number and (p-1) 
must be an even, i.e., (p-1)/2 must be an integer.

Suppose a square root of n under modulo p exists, then
there must exist an integer x such that,
      x2 % p = n % p 
or, 
     x2 ? n mod p

Raising both sides to power (p-1)/2,
      (x2)(p-1)/2 ? n(p-1)/2 mod p           
      xp-1 ? n(p-1)/2 mod p

Since p is a prime, from Fermat's theorem, we can say that 
   xp-1 ? 1 mod p

Therefore,
  n(p-1)/2 ? 1 mod p  

Time Complexity: O(logp) 
Auxiliary Space: O(1)
You may like to see below: 
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)

 



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 1 (When p is in form of 4*i + 3)
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 = 7Output: 3 or 4Explanation: 3 and 4 both are square roots of 2 under modulo 7 because (3*3)
14 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
Program to check for irreducibility using Eisenstein’s Irreducibility Criterion
Given an array arr[] consisting of N integers such that each array element arr[i] represent coefficients of a polynomial expression starting with the highest degree(A[0].X(N - 1) + A[1].X(N - 2) + ... + A[N - 2].X + A[N - 1]), the task is to check if the given equation is irreducible or not by Eisenstein's Irreducibility Criterion or not. If found
11 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
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
Euler's Four Square Identity
According to Euler's four square identity, the product of any two numbers a and b can be expressed as a sum of four squares if a and b both can individually be expressed as the sum of four squares.Mathematically, if a = [Tex]c1^2 + c2^2 + c3^2 + c4^2 [/Tex]and b = [Tex]d1^2 + d2^2 + d3^2 + d4^2 [/Tex]Then, a * b = [Tex]e1^2 + e2^2 + e3^2 + e4^2 [/T
15+ 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
Check if a number is Euler Pseudoprime
Given an integer N and a base number A, the task is to check whether N is a Euler Pseudoprime to the given base A. An integer N is called Euler Pseudoprime to the base A, if A > 0 and N is an odd composite number.A and N are co-prime i.e. GCD(A, N) = 1.A(N - 1) / 2 % N is either 1 or N - 1. Examples: Input: N = 121, A = 3 Output: YesInput: N = 3
9 min read
Check if Euler Totient Function is same for a given number and twice of that number
Given an integer N, the task is to check whether the Euler’s Totient Function of N and 2 * N are the same or not. If they are found to be the same, then print “Yes”. Otherwise, print “No”. Examples: Input: N = 9 Output: Yes Explanation: Let phi() be the Euler Totient function Since 1, 2, 4, 5, 7, 8 have GCD 1 with 9. Therefore, phi(9) = 6. Since 1,
7 min read
Why do we check up to the square root of a number to determine if that number is Prime?
Why do we check up to the square root of a number to determine if that number is prime?Prime numbers are natural numbers greater than 1 which are divisible only by 1 and itself. Examples include 2, 3, 5, 7, 11, 13, etc. (1 is neither prime nor composite). Here is the code to check whether a number is prime or not. As, the loop checks for each numbe
3 min read
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 <= N <= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Euler Method for solving differential equation
Given a differential equation dy/dx = f(x, y) with initial condition y(x0) = y0. Find its approximate solution using Euler method. Euler Method : In mathematics and computational science, the Euler method (also called forward Euler method) is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial v
6 min read
Euler Tour of Tree
A Tree is a generalization of connected graph where it has N nodes that will have exactly N-1 edges, i.e one edge between every pair of vertices. Find the Euler tour of tree represented by adjacency list. Examples: Input : Output : 1 2 3 2 4 2 1 Input : Output : 1 5 4 2 4 3 4 5 1 Euler tour is defined as a way of traversing tree such that each vert
6 min read
Euclid Euler Theorem
According to Euclid Euler Theorem, a perfect number which is even, can be represented in the form [Tex](2^n - 1)*(2^n / 2) )) [/Tex]where n is a prime number and [Tex]2^n - 1 [/Tex]is a Mersenne prime number. It is a product of a power of 2 with a Mersenne prime number. This theorem establishes a connection between a Mersenne prime and an even perf
10 min read
Euler tour of Binary Tree
Given a binary tree where each node can have at most two child nodes, the task is to find the Euler tour of the binary tree. Euler tour is represented by a pointer to the topmost node in the tree. If the tree is empty, then value of root is NULL. Examples: Input : Output: 1 5 4 2 4 3 4 5 1 Approach: First, start with root node 1, Euler[0]=1 Go to l
7 min read
Total nodes traversed in Euler Tour Tree
Euler tour of tree has been already discussed which flattens the hierarchical structure of tree into array which contains exactly 2*N-1 values. In this post, the task is to prove that the degree of Euler Tour Tree is 2 times the number of nodes minus one. Here degree means the total number of nodes get traversed in Euler Tour. Examples: Input: Outp
7 min read
Predictor-Corrector or Modified-Euler method for solving Differential equation
For a given differential equation [Tex]\frac{dy}{dx}=f(x, y) [/Tex]with initial condition [Tex]y(x_0)=y_0 [/Tex]find the approximate solution using Predictor-Corrector method.Predictor-Corrector Method : The predictor-corrector method is also known as Modified-Euler method. In the Euler method, the tangent is drawn at a point and slope is calculate
13 min read
Count integers in a range which are divisible by their euler totient value
Given 2 integers L and R, the task is to find out the number of integers in the range [L, R] such that they are completely divisible by their Euler totient value.Examples: Input: L = 2, R = 3 Output: 1 [Tex] [/Tex](2) = 2 => 2 % [Tex] [/Tex](2) = 0 [Tex] [/Tex](3) = 2 => 3 % [Tex] [/Tex](3) = 1 Hence 2 satisfies the condition.Input: L = 12, R
6 min read
Euler zigzag numbers ( Alternating Permutation )
Euler Zigzag numbers is a sequence of integers which is a number of arrangements of those numbers so that each entry is alternately greater or less than the preceding entry.c1, c2, c3, c4 is Alternating permutation where c1 < c2 c3 < c2 c3 < c4...zigzag numbers are as follows 1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521 ......For a given
7 min read
Euler's Factorization method
Given a number N, the task is to find the factors of N. Examples: Input: N = 1000009 Output: 293 3413 Explanation: 293 * 3413 = 1000009Input: N = 100000 Output: 800 125 Explanation: 800 * 125 = 100000 Euler's Factorization method: Euler's factorization method works on the principle that all the numbers N which can be written as the sum of two power
15+ min read
Conversion of an Undirected Graph to a Directed Euler Circuit
Given an undirected graph with V nodes (say numbered from 1 to V) and E edges, the task is to check whether the graph is an Euler Graph or not and if so then convert it into a Directed Euler Circuit. A Directed Euler Circuit is a directed graph such that if you start traversing the graph from any node and travel through each edge exactly once you w
10 min read
Count of elements having Euler's Totient value one less than itself
Given an array arr[] of N integers, and a range L to R, the task is to find the total number of elements in the array from index L to R that satisfies the following condition: [Tex]F(arr[i]) = arr[i] - 1 [/Tex] where F(x) is Euler's Totient Function. Examples: Input: arr[] = {2, 4, 5, 8}, L = 1, R = 3 Output: 2 Explanation: Here in the given range,
9 min read
Probability of Euler's Totient Function in a range [L, R] to be divisible by M
Given three integers L, R, and M, the task is to find the probability of Euler's Totient Function of a number in the range [L, R] is divisible by M. Euler’s Totient function is the count of numbers in {1, 2, 3, …, N} that are relatively prime to N, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1. Examples: Input: L = 1, R = 5, M =
12 min read