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



In this problem, we are given two values n and a prime number p. Our task is to find Square Root under Modulo p (When p is in form of 4*i + 3). Here, p is of the form (4*i + 3) i.e. p % 4 = 3 for i > 1 and p being a prime number.

Here are some numbers, 7, 11, 19, 23, 31...

Let's take an example to understand the problem,

Input : n = 3, p = 7
Output :

Solution Approach

A simple solution to the problem is using a loop. We will loop from 2 to (p - 1). And for every value, check if its square is square root under modulo p is n.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
void findSquareRootMod(int n, int p) {
   n = n % p;
   for (int i = 2; i < p; i++) {
      if ((i * i) % p == n) {
         cout<<"Square root under modulo is "<<i;
         return;
      }
   }
   cout<<"Square root doesn't exist";
}
int main(){
   int p = 11;
   int n = 3;
   findSquareRootMod(n, p);
   return 0;
}

Output

Square root under modulo is 5

One more method is directly using the formula,

If p is of the form (4*i + 3) and for square root to exist it will be $+/-n^{(p+1)/4}$

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int calcPowerVal(int x, int y, int p) {
   int res = 1;
   x = x % p;
   while (y > 0) {
      if (y & 1)
      res = (res * x) % p;
      y /= 2;
      x = (x * x) % p;
   }
   return res;
}
void squareRoot(int n, int p) {
   if (p % 4 != 3) {
      cout << "Invalid Input";
      return;
   }
   n = n % p;
   int sr = calcPowerVal(n, (p + 1) / 4, p);
   if ((sr * sr) % p == n) {
      cout<<"Square root under modulo is "<<sr;
      return;
   }
   sr = p - sr;
   if ((sr * sr) % p == n) {
      cout << "Square root is "<<sr;
      return;
   }
   cout<<"Square root doesn't exist ";
}
int main() {
   int p = 11;
   int n = 4;
   squareRoot(n, p);
   return 0;
}

Output

Square root under modulo is 9

Advertisements