# Pollard's Rho algorithm

I'm working in Mathematica and I'm trying to implement the [Pollard's Rho Algorithm for the Discrete Logartihm Problem][1].

Try using the Which function:

f[0] = 1;
f[x_] :=
Which[
Mod[x, 3] == 1, h*f[x-1],
Mod[x, 3] == 2, f[x-1]^2,
Mod[x, 3] == 0, g*f[x-1] ]


This will take input x and return the first condition which evaluates true

You can chain Ifs together: If[(condition1), (something), If[(condition2), (something else), If[(condition3), (another thing), (otherwise)]]] or use Which or Switch but I think you're better off using conditioned patterns (patterns that use /;). For example,

With[{h=foo,g=baz},(* <-- since I don't know the actual values *)
PollardX[0]=1;
PollardX[i_]:=h PollardX[i-1]/;Mod[i,3]==1;
PollardX[i_]:=  PollardX[i-1]^2/;Mod[i,3]==2;
PollardX[i_]:=g PollardX[i-1]/;Mod[i,3]==0;
]


And now

PollardX/@Range[8]
(* yields {foo,foo^2,baz foo^2,baz foo^3,baz^2 foo^6,baz^3 foo^6,baz^3 foo^7,baz^6 foo^14}*)

• An interesting post about the placement of Condition (/;): 533. Oct 12 '15 at 22:03
• That's a good discussion! I usually read /; test as "...only if test", which nicely (in my mind) goes at the end of sentences. Oct 13 '15 at 1:12