您的位置:首页 > 其它

UVALive - 7457 Discrete Logarithm Problem 费马小定理+暴力枚举+快速幂

2017-10-28 18:22 417 查看
由 费马小定理可知:

a ^ b % m  = a ^ ( b % (m-1) ) % m ;

(费马小定理:m是质数时  a ^ (m-1) % m = 1)

所以对于本题 枚举 a 的 1 - p  次幂对 p 取模,

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>

using namespace std;

typedef long long ll;
const int maxn = 10 + 7, INF = 0x3f3f3f3f, mod = 1e9 + 7;

ll p, a, b, x;

bool solve(ll n) {
//cout << n << " ";
ll ans = 1;
ll t = a;
while(n) {
if(n & 1) ans *= t, ans %= p;
t = t * t; t %= p;
n /= 2;
}
//cout << ans << " == " << endl;
if(ans == b) return true;
else return false;
}

int main() {
ios::sync_with_stdio(0);

cin >> p;
while(cin >> a && a) {
cin >> b;
int f = 0;
for(ll i = 1; i < p; ++i) {
if(solve(i)) { cout << i << endl; f = 1; break;}
}
if(!f) cout << 0 << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: