Hello all, I am trying to solve this https://www.spoj.pl/problems/MOD/15 in haskell but getting TLE. I just want to know if this problem is solvable in Haskell or not ? I have implemented baby step giant step algorithm http://www.cs.sjsu.edu/~stamp/crypto/PowerPoint_Mac/5 19_DiscreteLog.ppt. Here is my source code.
import Data.List
--a^x=b mod p
modpoW::Integer->Integer->Integer->Integer
modpoW a 0 n=1
modpoW a d n= fun a d where
fun a 1 = mod a n
fun a 2 = mod (a^2) n
fun a d = let
p=fun (mod (a^2) n) (div d 2)
q=if odd d then mod (a*p) n else p
in mod q n
extendedgcD::Integer->Integer->Integer
extendedgcD a b=
let
[u,v,d]=exgcD a b where
exgcD a b | mod a b == 0 = [0,1,b]
| otherwise = [y,x-y*(div a b),z]
where
[x,y,z] = exgcD b (mod a b)
in if d<0 then -u else u
babysteP a b p=
let
m=ceiling.sqrt.fromIntegral $ (p-1)
u=extendedgcD a p
bm=[(i,mod (b*modpoW u (i*m) p) p)|i<-[0..(m-1)]]
in recfuN a p m 0 bm
recfuN a p m cnt bm
| cnt>=m = -1
|otherwise = case find (\(x,y)->y == modpoW a cnt p) bm of
Just (x,y)->x*m+cnt
_-> recfuN a p m (cnt+1) bm
main=do
line<-fmap words getLine
let a=read (line!!0)::Integer
p=read (line!!1)::Integer
b=read (line!!2)::Integer
case and [a==0,b==0,p==0] of
False-> do
if gcd a p /=1 then putStrLn $ snd (1,"No Solution") else print $ fst(babysteP a b p,"")
main
_ -> return ()
created
last reply
- 4
replies
- 876
views
- 3
users
- 5
links