Skip to content

Commit 89512e6

Browse files
authored
Update Discrete Logarithm.cpp
1 parent 242e980 commit 89512e6

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Discrete Logarithm.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,68 @@ int discreteLog(int a, int b, int m)
5050
}
5151
}
5252

53+
------------------------------------------------------------------------------------------------------------------------------------
54+
//Faster Implementation
55+
56+
#include <bits/stdc++.h>
57+
#include <ext/pb_ds/assoc_container.hpp>
58+
using namespace __gnu_pbds;
59+
using namespace std;
60+
61+
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
62+
#define endl "\n"
63+
#define int long long
64+
65+
long long pow(long long a, long long b, long long m)
66+
{
67+
long long ans=1;
68+
while(b)
69+
{
70+
if(b&1)
71+
ans=(ans*a)%m;
72+
b/=2;
73+
a=(a*a)%m;
74+
}
75+
return ans;
76+
}
77+
78+
int discreteLog(int a, int b, int m)
79+
{
80+
a %= m, b %= m;
81+
if(b == 1)
82+
return 0;
83+
int cnt = 0;
84+
long long t = 1;
85+
for(int curg=__gcd(a, m);curg!=1;curg=__gcd(a, m))
86+
{
87+
if(b % curg)
88+
return -1;
89+
b /= curg, m /= curg, t = (t * a / curg) % m;
90+
cnt++;
91+
if(b == t)
92+
return cnt;
93+
}
94+
95+
gp_hash_table<int, int> hash;
96+
int mid = ((int)sqrt(1.0 * m) + 1);
97+
long long base = b;
98+
for(int i=0;i<mid;i++)
99+
{
100+
hash[base] = i;
101+
base = base * a % m;
102+
}
103+
104+
base = pow(a, mid, m);
105+
long long cur = t;
106+
for(int i=1;i<=mid+1;i++)
107+
{
108+
cur = cur * base % m;
109+
auto it = hash.find(cur);
110+
if(it != hash.end())
111+
return i * mid - it->second + cnt;
112+
}
113+
}
114+
53115
//Problem 1: https://codeforces.com/gym/101853/problem/G
54116
//Solution 1: https://codeforces.com/gym/101853/submission/50273547
55117

0 commit comments

Comments
 (0)