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;
}
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;
}
相关文章推荐
- UVALive 7457 Discrete Logarithm Problem (暴力枚举)
- UVaLive 7457 Discrete Logarithm Problem (暴力)
- UVALive Problem 7457 Discrete Logarithm Problem——Regionals 2015 :: Asia - Taipei
- UVALive 7457 Discrete Logarithm Problem
- UVALive Problem 7079 How Many Maos Does the Guanxi Worth(暴力枚举+最短路)——2014ACM/ICPC亚洲区广州站
- 数学 ( 解高次同余方程 )——Discrete Logarithm Problem ( UVA 7457 )
- UVALive 6659 Dromicpalin Substrings (递推 + 暴力枚举)
- LA 7457 Discrete Logarithm Problem(shank的大步小布算法)
- LA 7457 Discrete Logarithm Problem
- POJ1964/UVALive 3029 -City Game -求最大子矩形-(暴力枚举/dp)
- UVA 105 - The Skyline Problem(暴力枚举)
- UVALive 6163(暴力枚举)
- UVALive 6912 Prime Switch 暴力枚举+贪心
- UVA 592 逻辑之岛(暴力枚举)
- UVaLive 6623 Battle for Silver (最大值,暴力)
- UVALive 7279 Sheldon Numbers(位运算、暴力)
- 【暴力预处理+剪枝/bitset】Golf Bot UVALive - 6886
- uvaLive 3401 Colored Cubes 暴力
- UVALive 6855 Banks (暴力)
- UVALive 6092 Catching Shade in Flatland --枚举+几何计算