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_] := 
    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[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

(* 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}*)
  • $\begingroup$ An interesting post about the placement of Condition (/;): 533. $\endgroup$ Oct 12 '15 at 22:03
  • $\begingroup$ That's a good discussion! I usually read /; test as "...only if test", which nicely (in my mind) goes at the end of sentences. $\endgroup$
    – evanb
    Oct 13 '15 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.