C++實現模p下的平方根計算(p為4i+3形式)
在這個問題中,我們給定兩個值n和一個素數p。我們的任務是在模p下找到平方根(當p為4*i + 3的形式時)。這裡,p的形式為(4*i + 3),即p % 4 = 3,其中i > 1,p為素數。
例如一些這樣的數:7, 11, 19, 23, 31...
讓我們來看一個例子來理解這個問題:
Input : n = 3, p = 7 Output :
解決方案方法
解決這個問題的一個簡單方法是使用迴圈。我們將從2迴圈到(p - 1)。對於每個值,檢查它的平方是否為模p下的平方根n。
示例
程式演示了我們解決方案的工作原理
#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;
}輸出
Square root under modulo is 5
另一種方法是直接使用公式:
如果p的形式為(4*i + 3),並且平方根存在,則它將為$+/-n^{(p+1)/4}$
示例
程式演示了我們解決方案的工作原理
#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;
}輸出
Square root under modulo is 9
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP