text: Find Square Root under Modulo p | Set 1 ( When p is in form of 4 * i + 3 ) | Utility function to do modular exponentiation . It returns ( x ^ y ) % p . ; res = 1 Initialize result x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Returns true if square root of n under modulo p exists . Assumption : p is of the form 3 * i + 4 where i >= 1 ; Try " + ( n ^ ( ( p ▁ + ▁ 1 ) / 4 ) ) " ; Try " - ( n ▁ ^ ▁ ( ( p ▁ + ▁ 1 ) / 4 ) ) " ; If none of the above two work , then square root doesn 't exist ; Driver Code
code: def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def squareRoot ( n , p ) : NEW_LINE INDENT if ( p % 4 != 3 ) : NEW_LINE INDENT print ( " Invalid ▁ Input " ) NEW_LINE return NEW_LINE DEDENT n = n % p NEW_LINE x = power ( n , ( p + 1 ) // 4 , p ) NEW_LINE if ( ( x * x ) % p == n ) : NEW_LINE INDENT print ( " Square ▁ root ▁ is ▁ " , x ) NEW_LINE return NEW_LINE DEDENT x = p - x NEW_LINE if ( ( x * x ) % p == n ) : NEW_LINE INDENT print ( " Square ▁ root ▁ is ▁ " , x ) NEW_LINE return NEW_LINE DEDENT print ( " Square ▁ root ▁ doesn ' t ▁ exist ▁ " ) NEW_LINE DEDENT p = 7 NEW_LINE n = 2 NEW_LINE squareRoot ( n , p ) NEW_LINE